0

MyProperty1MyPropertySelectedMyProperty2に基づいて表示したい。条件文を使用する方法、ifまたはMyPropertySelectedelseに基づく方法は?ありがとう。

// [Browsable(true)
// ????? conditional statement IF ELSE in here..
// IF (MyPropertySelected) MyProperty1 will be show ELSE MyProperty2 will be show.
public bool MyPropertySelected { get; set; }

// [Browsable(true) or [Browsable(false) depending on MyPropertySelected condition.
public int MyProperty1 { get; set; }

// [Browsable(true) or [Browsable(false) depending on MyPropertySelected condition.
public int MyProperty2 { get; set; }
4

2 に答える 2

5

あなたはリンゴとオレンジを混同しています。

属性はメタデータであり、プロパティ値は実行時にその値を取得します。

言い換えると、属性はリフレクションを使用してアクセスするものであり、特定のオブジェクトではなく、オブジェクトのタイプ(つまりクラス)に関連付けられています。

もう1つの問題は、コンパイル時に機能しない条件に基づいて、プロパティに属性を追加することです。

MyPropertySelected囲んでいるクラスがインスタンス化されるまで、値は取得されません。つまり、オブジェクトが作成されます。たとえば、次のようにMyClass a = new MyClass()なります。つまり、属性を追加するかどうかは、コンパイル時の選択にはなりません

明確にしておきたいのですが、純粋に属性を使用してやりたいことを行うことはできません。

実行時の値に基づいて条件付きで属性を適用することはできません

Browsable最後に、あなた自身の質問が言うように、あなたは条件に基づいて何かを作りたいのではないかと思います。あなたはそれをすることはできません。

わかった、でも何…?

別のソフトウェア設計を使用して、状況を回避できます。

1)

まず、閲覧可能かどうかに関係なく、任意のプロパティを持つインターフェイスを作成します。[Browsable(bool)]ただし、属性をインターフェイスプロパティに適用しないでください。

2)

以前に作成したインターフェイスを実装する2つのクラスを作成します。

最初のクラスでは、インターフェイスプロパティを実装し、[Browsable(true)]それらに属性を設定します。2番目のクラスでも同じことをしますが、今回は[Browsable(false)]それらを装着します。

3)

オブジェクトのインスタンスを作成するコードの中には、インスタンス化するコードも決定するものがあります

つまりMyPropertySelected、両方のクラスの外部に外部化し、呼び出し元で条件切り替え全体を実行します。

public interface IBrowsableProperties
{
   int Property1 { get;set; }
   int Property2 { get;set; }
}

public class A : IBrowsableProperties
{ 
   [Browsable(true)]
   public int Property1 { get;set; }

   [Browsable(true)]
   public int Property1 { get;set; }
}

public class B : IBrowsableProperties
{
   [Browsable(false)]
   public int Property1 { get;set; }

   [Browsable(false)]
   public int Property1 { get;set; }
}

// Somewhere in some method...
bool propertySelected = true;

IBrowsableProperties instance = null;

if(propertySelected) 
{
   instance = new A();
}
else
{
   instance = new B();
}

// ... do stuff with your instance of IBrowsableProperties!

アップデート

私はあなたの質問のコメントのいくつかを検討しました、そして私はあなたがPropertyGridコントロールで働いているのを見つけました。

とにかく、あなたはあなたのケースに概念を適用することができます。PropertyGrid継承することができます。PropertyGrid1提案されたインターフェースを実装する両方のクラスとPropertyGrid2派生クラスを作成できます。

于 2012-12-03T14:33:13.953 に答える
2

おそらく、次のような中間プロパティが必要です。

class Foo
{
    public bool MyPropertySelected
    {
        get;
        set;
    }

    public readonly int MyProperty
    {
        get 
        {
            return MyPropertySelected ? MyProperty1 : MyProperty2;
        }
    }

    private int MyProperty1
    {
        get;
        set;
    }

    private int MyProperty2
    {
        get;
        set;
    }
}
于 2012-12-03T14:08:58.933 に答える