不可变类型的配置属性属性、类型

2023-09-05 00:02:42 作者:阳光不暖人心

是否有可能使用一成不变的类型,配置属性与.NET的配置API?

Is it possible to use immutable types as configuration properties with .NET's configuration API?

让我们说我有一个不变的类型,称为MyClass的:

Let's say I have an immutable type called MyClass:

public class ImmutableClass
{
    private readonly int value;

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

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

我想用这种类型的配置节配置属性:

I would like to use this type as a configuration property in a ConfigurationSection:

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

当我这样做,我不能序列化和反序列化MyConfigurationSection,因为它引发此异常:

When I do this, I can't serialize and deserialize MyConfigurationSection because it throws this exception:

System.Configuration.ConfigurationErrorsException:财产'标准'的值不能转换为字符串。错误是:找不到一个支持转换到/从字符串类型FindCriterion财产标准转换器

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'.

如果我得到ImmutableClass自ConfigurationElement,我当我尝试序列化和反序列化配置部分获得此异常:

If I derive ImmutableClass from ConfigurationElement, I get this exception when I try to serialize and deserialize the configuration section:

System.Reflection.TargetInvocationException:异常被抛出调用的目标。 ---> System.Reflection.TargetInvocationException:异常被抛出调用的目标。 ---> System.MissingMethodException:此对象定义无参数的构造函数

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,故取其接口需要,我可以实现。

I have full control over ImmutableClass, so I can implement whichever interface is needed.

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

Is there any way I can hook into the configuration API so that ImmutableClass can be used in this way?

推荐答案

您可能能够使用一些的类型转换器,以帮助沿(链接到System.Configurations.ConfigurationConverter)的过程。

You might be able to use some TypeConverters to help the process along (link to System.Configurations.ConfigurationConverter).

真正的问题是,为什么你要自己造成这么大的麻烦?只是有一些时间在那里它能够更好地躺下来,把它比投入了战斗。如果你试图做什么办法比具体的一个奠定了你其他框架的某些部分是令人沮丧的......

The real question is why do you want to cause yourself so much trouble? There are just some times where its better to lay back and take it than put up a fight. Some parts of the framework are frustrating if you try to do it any way other than the specific one laid out for you....