c# - 如何获取 ConfigurationSection 属性作为 System.Type

标签 c# configurationmanager

我想定义一个自定义配置部分,并有一个属性不产生一个字符串,而是一个 system.type(如果用户输入一堆垃圾,则为 null)

例如:

<myCustomConfig myAnnoyingType="System.String" />

在 C# 中(在当前的现实世界中)

[ConfigurationProperty("myAnnoyingType")]
public string MyAnnoyingType
{
   get { return (string)this["myAnnoyingType"]; }
}

// else where in the app
var stringType = thatConfig.MyAnnoyingType
var actualType = Type.GetType(stringType);
// wow that was boring.

在 C# 中(在理想世界中)

[ConfigurationProperty("myAnnoyingType")]
public Type MyAnnoyingType
{
    get { return (Type)this["myAnnoyingType"]; }
}

我想要的是不必在 C# 中将项目作为字符串保存,然后在应用程序中将其转换为类型;我希望这作为 ConfigurationManager 职责的一部分自动完成。

这可能吗?如果必须的话,我可以使用 TypeConverter,将它保留为字符串然后在应用程序中进行类型查找似乎太弱了。这并不难做,只是当我知道我正在寻找一种类型时似乎毫无意义,必须明确地做它的值(value)是什么。

最佳答案

尝试使用将为您进行转换的 TypeConverterAttribute。这对我有用。

    [ConfigurationProperty("type")]
    [TypeConverter(typeof(TypeNameConverter))]
    public Type Type
    {
        get
        {
            return (System.Type)this["type"];
        }
        set
        {
            this["type"] = value;
        }
    }

关于c# - 如何获取 ConfigurationSection 属性作为 System.Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31196028/

相关文章:

asp.net-mvc - ConfigurationManager 读取错误的文件 - Web.config 而不是 App.config

c# - 克隆通用 ConfigurationSection 而不使用自定义类

c# - 使用 ConfigurationManager 将用户值存储在独立于应用程序配置的文件中

c# - asp.net 从 List<> 方法获取值

c# - 使用 LINQ 从文件中读取文本数据

c# - 保留从客户收到的大数据直至处理

c# - 为什么在运行时没有考虑我在 App.config 中对 AppSettings 的更改? (控制台应用程序)

c# - 从 asp.net 读取配置文件

c# - C# 中的动态类型

c# - MS 图表控件 : Position grid lines between labels