gpt4 book ai didi

c# - 使用 ConfigurationPropertyAttribute 避免重复属性名称 3 次

转载 作者:行者123 更新时间:2023-12-02 22:43:18 25 4
gpt4 key购买 nike

在代码中重复 ConfigurationPropertyAttribute 名称三遍让我很困扰。
很容易错过拼写错误或复制/粘贴属性而忘记更新名称的一个实例。

声明一个常量只能解决其中一个问题。有没有更好的办法?

我试过反射,但是枚举属性似乎更麻烦,也更难看。

[ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
[IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
public int Port
{
get
{
return (int)this["port"];
}
set
{
this["port"] = value;
}
}

我知道 DRY 只是一个原则,在现实世界中,原则往往必须让位于实用主义。但我确定有人有更清洁的方法?

最佳答案

如果需要,您可以对配置元素使用非声明性方法。示例可以在整个 Internet 上找到 - 特别是在 Unraveling the Mysteries of .NET 2.0 Configuration。其中示例同时显示了这两种方法。

class MyConfigurationElement : ConfigurationElement
{
private static ConfigurationPropertyCollection _properties = new ConfigurationPropertyCollection();
private static ConfigurationProperty _portProperty = new COnfigurationProperty("port", ..... ); // Will leave as example for you to add validator etc.

static MyConfigurationElement()
{
_properties.Add(_portProperty);
}

protected override ConfigurationPropertyCollection Properties
{
get { return _properties; }
}

public int Port
{
get
{
return (int)this[_portProperty];
}
set
{
this[_portProperty] = value;
}
}
}

关于c# - 使用 ConfigurationPropertyAttribute 避免重复属性名称 3 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10436041/

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