【问题标题】:Unable to find a converter that supports conversion to/from string for the property of type 'Type'找不到支持“类型”类型属性的字符串转换为/从字符串转换的转换器
【发布时间】:2011-01-20 07:03:05
【问题描述】:

我正在用 C# 和 .NET 3.5 编写自定义配置类。属性之一应为 System.Type 类型。当我运行代码时,我得到了标题中提到的错误。

[ConfigurationProperty("alertType", IsRequired = true)]
public Type AlertType
{
    get { return (Type)this["alertType"]; }
    set { this["alertType"] = value; }
}

配置文件如下所示:

<add name="Name" pollingInterval="60" alertType="Namespace.ClassName, Company.Project" />

.net 框架能够将字符串转换为 System.Type,因为配置文件的 configSections 具有类型属性。问题是他们是怎么做到的。

【问题讨论】:

    标签: c# .net-3.5


    【解决方案1】:

    我知道这是旧的,但我认为这实际上是正确的答案:

    [TypeConverter(typeof(TypeNameConverter))]
    [ConfigurationProperty("alertType", IsRequired=true)]
    public Type AlertType
    {
        get { return this[ "alertType" ] as Type; }
        set { this[ "alertType" ] = value; }
    }
    

    添加 TypeNameConverter 可以在不使用 Type.GetType() 的情况下实现从 String 到 Type 的转换。

    【讨论】:

    • 是的,由于某种原因,已接受的解决方案对我不起作用,但确实如此。
    【解决方案2】:

    【讨论】:

    • 有时我们试图看起来太努力,答案就在我们面前:)
    【解决方案3】:

    您可以尝试使用TypeNameConverter 类。它有两种你可能感兴趣的方法:

    ConvertToStringConvertFromString

    【讨论】:

      猜你喜欢
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2014-02-22
      • 1970-01-01
      相关资源
      最近更新 更多