Why in C# this is not allowed in member initialize

2020-08-10 04:36发布

问题:

I'm converting a VB.Net app into C#, and have noticed that in the VB.Net code, there is a private member variable, which is initialised using Me like this:

Private m_ClassA As New MyCollection(Of ClassA)(Me)

When I convert this to C# code like this:

private MyCollection<ClassA> _classA = new MyCollection<ClassA>(this);

I have the error

Argument is value while parameter type is ref.

If I put ref in front of the parameter this, I get the error

cannot use this in member initializer.

I've read here that members are initialized before the base class, and so this cannot be used in members as it may not yet be initialised. My question is why is it legal in VB.Net and not C#?

Is this down to the compiler handling it differently? It seems weird that the two have different behaviours.

To get around it I guess i'll initialize the member in the contructor.

回答1:

According to MSDN.

A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor.

This can be read here.

You can't access this anywhere really other than instance/constructors. So you couldn't do something like this either:

public class Foo
{
  private Foo _foo = this;
}

As you say, in C# your going to have to use methods/constructors.

public class Foo
{
  private Foo _foo;
  public Foo()
  {
    _foo = this;
  }
  public void InitializeFoo()
  {
    _foo = this;
  }
}

MSDN also states the following for Me:

The Me keyword provides a way to refer to the specific instance of a class or structure in which the code is currently executing. Me behaves like either an object variable or a structure variable referring to the current instance.

It sounds like once the class has executed you get access to this, but only within the instance methods whereas in VB.NET you get access at the time the class is executing, hence the reason why you can't use it as you have stated.



回答2:

VB existed before .NET and VB.NET, so some features existed that developers did not want to remove when .NET was introduced. Another such feature is "On Error Resume Next", which also does not exist in C#.



标签: c# vb.net