1

次のコードでは

// MVVM Views part class
public partial class DashBoard : UserControl
{
    public DashBoard()
    {
        InitializeComponent();
        this.DataContext = new DashBoardViewModel();
    }
}

this.DataContext の代わりに base.DataContext を使用できますか。これの代わりに base を使用できるのはどのような場合ですか?

4

4 に答える 4

3

It's usually clearer to use this. You normally only specify base when you want to explicitly call a base class constructor or the base implementation of an overridden method or property.

Using base.DataContext would work, but it would might imply that this.DataContext would mean something different.

于 2012-05-25T07:26:36.137 に答える
2

You use this to access a method defined in the present class (or superclass if it's not in the present class). You use base to access a method in the superclass or higher. In this case you could have used either (or none as Marc points out above).

I prefer to emit this except when it's (rarely) required.

于 2012-05-25T07:27:28.307 に答える
1

あなたのケースを考慮して、クラスDashBoardのDataContextプロパティを何らかの値で初期化しようとしています。そのため、 (base)UserControlクラス オブジェクトのDataContext型付きプロパティを呼び出しても、初期化されません。したがって、どのプロパティを初期化するかを決定するには、プログラムのロジックを調べる必要があります。

基本的に、MSDN は、次の 2 つのシナリオで (base.) を使用する必要があることを示しています。 -別のメソッドによってオーバーライドされた基本クラスのメソッドを呼び出します。-派生クラスのインスタンスを作成するときに、どの基本クラス コンストラクターを呼び出すかを指定します。私の実践では、(この)メソッドが例外で終了する最初のシナリオを使用しました。より一般的な(ベース)メソッドを呼び出そうとしていました。幸運を!

于 2012-05-25T08:31:09.117 に答える
1

他の人が言ったことに追加するには、ベース。overrides または new キーワードのいずれかを使用して基本クラスから何かをオーバーライドした場合に使用されます。元のメソッドにアクセスするには base を使用する必要があります。

class a
{
   public virtual void method1()
   {
   }

   public string property1 { get; set; }
}

class b : a
{
    // this has it's own instance in b, the only way to get to
    // the original property1 is with base (or reflection)
    public new string property1 { get; set; }

    public override void method1()
    {
       // the only way to get to the original method1 and property1
       base.method1();
       base.property1 = "string";
    }
}

あなたの例では、DataContext プロパティがこれらのキーワードのいずれかを使用している場合、 base と this はまったく同じことを意味しません。

于 2012-05-25T07:40:15.010 に答える