Virtual/Abstract fields in C#

前端 未结 9 1212
逝去的感伤
逝去的感伤 2020-12-16 10:19

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

9条回答
  •  悲&欢浪女
    2020-12-16 10:26

    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.

提交回复
热议问题