[英]How do I get ConfigurationSection property as a System.Type
i want to define a custom configuration section and have a property not yield a string but a system.type (or null if the user types in a load of rubbish) 我想定义一个自定义配置部分,并且有一个属性不会产生字符串,而是一个system.type(如果用户输入了一堆垃圾,则为null)
eg: 例如:
<myCustomConfig myAnnoyingType="System.String" />
in the C# (in the current real world) 在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.
in the C# (in an ideal world) 在C#中(在理想世界中)
[ConfigurationProperty("myAnnoyingType")]
public Type MyAnnoyingType
{
get { return (Type)this["myAnnoyingType"]; }
}
What I want is NOT to have to keep the item as a string in the C# and then convert that into a Type in the application; 我想要的不是必须将项目保存为C#中的字符串,然后将其转换为应用程序中的Type; i'd like this to be done automatically as part of the responsibility of the ConfigurationManager.
我希望这是作为ConfigurationManager职责的一部分自动完成的。
Is this possible? 这可能吗? I'm OK to use a TypeConverter if I have to be, it just seems so weak to keep it as a string and then do the type lookup in the application.
如果必须的话,我可以使用TypeConverter,只是将它保持为字符串似乎很弱,然后在应用程序中进行类型查找。 It's not hard to do, just seems pointless when I know i'm looking for a type, what is the value of having to explicitly do it.
这不难做到,当我知道我正在寻找一种类型时,似乎毫无意义,必须明确地做它的价值。
Try using a TypeConverterAttribute that will do the conversion for you. 尝试使用将为您进行转换的TypeConverterAttribute。 This worked for me.
这对我有用。
[ConfigurationProperty("type")]
[TypeConverter(typeof(TypeNameConverter))]
public Type Type
{
get
{
return (System.Type)this["type"];
}
set
{
this["type"] = value;
}
}
First, its better to define a type in your settings using the fully qualified name . 首先,最好使用完全限定名称在设置中定义类型。 This way you get less problems with resolving the
Type
from the string
. 这样,从
string
解析Type
就会减少问题。
Second, you need to find the Type
by it's string name as was already answered in Convert String to Type in C# because it's not possible just cast string
to Type
. 其次,您需要找到
Type
的字符串名称,因为在转换字符串中已经回答了C#中的类型,因为它不可能只是将string
为Type
。
In your case it would be: 在你的情况下,它将是:
[ConfigurationProperty("myAnnoyingType")]
public Type MyAnnoyingType
{
get { return Type.GetType(this["myAnnoyingType"]); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.