c# - 设置中的 XDocument

标签 c# xml visual-studio-2010 linq settings

我尝试在 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/

相关文章:

c++ - 如何在 Win32 控制台应用程序中将 Fmod 设置为非常基本的功能?

windows - Visual Studio 改变了它的字母表

C#:无法看到 Windows 注册表中的更改

c# - 更改 TextBox 文本时 ViewModel 属性未更新

java - ListView 滚动时覆盖 EditText

java - 在Android中使用输入流打开XML文件

c# - asp.net 页面上的预设格式。

c# - 使用 C# 模拟登录到 VBulletin 的操作

c# - 将字符串转换为正确的日期字符串

visual-studio-2010 - 如何使用 TFS 映射现有文件夹(已移动到新机器)而无需从 TFS 下载整个数据?