Virtual/Abstract fields in C#

2019-01-23 22:42发布

Is it possible to have a virtual/abstract field in a C# class? If so, how is it done?

10条回答
叛逆
2楼-- · 2019-01-23 23:33

It's possible however to just replace the new field. See this example:

public class Program
{
    public class A
    {
        public int f = 3;
    }

    public class B
    {
        public int f = 9;
    }

    public static void Main(string[] args)
    {            
        B bb = new B();
        Console.WriteLine(bb.f); // writes 9
    }
}
查看更多
乱世女痞
3楼-- · 2019-01-23 23:39

No, a field can only be assigned to not, overridden.

However, you could probably use a property and it would look almost the same

public class MyClass {
  public int MyField; //field
  public virtual int MyProperty { get; set; }  //property
}

both get used like so:

var x = new MyClass();
Debug.WriteLine("Field is {0}", x.MyField);
Debug.WriteLine("Property is {0}", x.MyProperty);

Unless the consumer is using reflection, it looks exactly the same.

查看更多
贪生不怕死
4楼-- · 2019-01-23 23:42

Fields are storage locations in a class - you cannot "override" them or make the virtual.

Properties, on the other hand can be made both virtual or abstract. Properties are simply syntactic sugar around get/set methods, which do the work of retrieving or setting the property value.

查看更多
相关推荐>>
5楼-- · 2019-01-23 23:43

An old question, but here are my 2 cents:

Though one might not be able to create a virtual field - one can achieve what the OP seems to be looking for, which is to have the derived class's field's value be different than the base's.

Simply assign it the "derived" value in the constructor.

(Though that won’t be enough if you have field initializers like int i = 1; int j = i;).

查看更多
登录 后发表回答