我尝试在 VS2010 的设置 Pane 中手动输入 XDocument
,但没有成功。类型为System.Xml.Linq.XDocument
我收到的消息是:
Cannot be converted to an instance of type 'System.Xml.Linq.XDocument'
有人知道解决这个问题的方法吗?
ST
最佳答案
您无法创建 XDocument
直接设置,因为XDocument
类不满足criteria设置用来确定是否可以使用某种类型:
Application settings can be stored as any data type that is XML serializable or has a TypeConverter that implements ToString/FromString. The most common types are String, Integer, and Boolean, but you can also store values as Color, Object, or as a connection string.
XDocument
提供了一种通过解析字符串来创建 XML 文档的方法,但它不是构造函数,而是静态 Load
方法(它需要 TextWriter
,而不是字符串)。因此它不适合在“设置”中使用。
但是您可以对其进行子类化,并为该子类提供一个类型转换器。幸运的是,子类化 XDocument
非常容易。使用类型转换器。首先,创建一个子类:
[TypeConverter(typeof(MyXDocumentTypeConverter))]
public class MyXDocument : XDocument
{
}
该类使用此 TypeConverter
:
public class MyXDocumentTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return (sourceType == typeof (string));
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
MyXDocument d = new MyXDocument();
d.Add(XDocument.Load(new StringReader((string) value)).Elements().First());
return d;
}
return null;
}
}
完成此设置后,您可以编写如下代码:
MyXDocument d = "<foo/>";
和字符串 <foo/>
将被传递到类型转换器并解析(通过 Load
)为 XDocument
,然后将其顶级元素添加到 MyXDocument
。这与 Settings.Designer.cs
中自动生成的代码分配相同。用途:
return ((global::XmlSettingsDemo.MyXDocument)(this["Setting"]));
现在您可以进入“设置”对话框并创建此类设置。您无法导航到“类型”对话框中的类型;您必须手动输入类型的全名( XmlSettingsDemo.MyXDocument
是我的名字)。
关于c# - 设置中的 XDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578131/