English 中文(简体)
这个还是这个基地? 在哪个情况下我们可以用这个基地代替这个基地?
原标题:this or base? In which case could we use base instead of this?

在以下代码中

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

我们能否使用基点. DataContext 代替这个. DataContext 。 在哪个情况下我们可以用基点代替这个?

最佳回答

使用 this 通常更清楚。通常,当您想要明确调用基级构建器或实施被覆盖的方法或属性时,您通常只指定 base

使用 base.DataContext work ,但它可能意味着 this.DataContext 将意味着不同的东西。

问题回答

您使用 < code> this 来访问当前类中定义的方法( 或如果不属于当前类的超级类 ) 。 您使用 < code> base 来访问超级类或更高类中的一种方法。 在这种情况下, 您本可以使用其中一种方法( 或上面的 Marc 点数没有使用 ) 。

我更愿意发出 this ,除非(非常)需要。

要添加其他人所说的话, 基础 。 当您用 overs 或新关键字从基准类中跳过某些内容时, 使用基数, 您需要使用基数访问原始方法 。

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 属性使用这些关键字中的任何一个, 则以该关键字为基础, 而这根本不意味着同样的事情 。

考虑到您的案件 u 正在尝试初始化“强” DataContext

Basicly MSDN tells that u should use (base.) in two scenarious: -Call a method on the base class that has been overridden by another method. -Specify which base-class constructor should be called when creating instances of the derived class. In my practise i used first scenario when (this) method ends with exception, i was trying to call more general (base) method. Good luck!





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签