gpt4 book ai didi

c# - 作为配置属性的不可变类型

转载 作者:太空狗 更新时间:2023-10-29 21:42:22 24 4
gpt4 key购买 nike

是否可以使用不可变类型作为 .NET 配置 API 的配置属性?

假设我有一个名为 MyClass 的不可变类型:

public class ImmutableClass
{
private readonly int value;

public ImmutableClass(int value)
{
this.value = value;
}

public int Value
{
get { return this.value; }
}
}

我想将此类型用作 ConfigurationSection 中的配置属性:

public class MyConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("foo")]
public ImmutableClass Foo
{
get { return (ImmutableClass)base["foo"]; }
set { base["foo"] = value; }
}
}

当我这样做时,我无法序列化和反序列化 MyConfigurationSection,因为它会引发此异常:

System.Configuration.ConfigurationErrorsException: The value of the property 'criterion' cannot be converted to string. The error is: Unable to find a converter that supports conversion to/from string for the property 'criterion' of type 'FindCriterion'.

如果我从 ConfigurationElement 派生 ImmutableClass,当我尝试序列化和反序列化配置部分时会遇到此异常:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MissingMethodException: No parameterless constructor defined for this object.

我可以完全控制 ImmutableClass,因此我可以实现任何需要的接口(interface)。

有什么方法可以连接到配置 API 以便以这种方式使用 ImmutableClass?

最佳答案

我个人认为最好将配置 部分 中的数据分开(看起来需要可变),以及如何在对象模型中表示它。没有什么能阻止您拥有两种表示形式 - 用于配置的简单 (DTO/POCO) 版本,以及用于在您的应用中实际使用的自定义版本(在本例中为不可变)。

关于c# - 作为配置属性的不可变类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1443988/

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