2

コード内で名前を3回繰り返すと、ConfigurationPropertyAttribute本当に気になります。
スペルミスを見逃したり、プロパティをコピーして貼り付けたりして、名前の1つのインスタンスを更新するのを忘れるのは簡単です。

定数を宣言すると、これらの問題の1つだけが解決されます。もっと良い方法はありますか?

リフレクションを試しましたが、属性を列挙するのはもっと面倒で醜いようでした。

[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は単なる原則であり、現実の世界では、原則が実用主義に取って代わらなければならないことがよくあります。しかし、誰かがよりクリーンな方法を持っていると確信していますか?

4

2 に答える 2

3

必要に応じて、構成要素に非宣言型のアプローチを使用できます。例はインターネット全体で見つけることができます。特に、例が両方の方法を同時に示している.NET2.0構成の謎を解き明かす場合に見られます。

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;
        }
    }    
}
于 2012-05-03T18:27:49.173 に答える
2

定数を使用しても3つの問題すべてが解決されないのはなぜですか?

例:

class MyConfigurationElement : ConfigurationElement
{

    // Use public, private or internal, as you see fit.
    private const string PortName = "port";

    // Add something like this, if you also want to access the string value
    // and don't want to recompile dependend assemblies when changing the
    // string 'port' to something else.
    // public static readonly PortNameProperty = PortName;

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

補足:構成セクションデザイナの使用も検討する場合。率直に言って、私は数年前にそれをテストしただけで、それ以来それを使用したことはありませんが、おそらくそれはDRYに関するあなたの懸念も解決します。

于 2012-05-03T18:14:09.777 に答える