gpt4 book ai didi

c# - 无法找到支持类型为 'Type' 的属性与字符串之间的转换的转换器

转载 作者:IT王子 更新时间:2023-10-29 04:25:34 27 4
gpt4 key购买 nike

我正在用 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 具有类型属性。问题是他们是怎么做到的。

最佳答案

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

[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 的转换。

关于c# - 无法找到支持类型为 'Type' 的属性与字符串之间的转换的转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2322074/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com