Virtual/Abstract fields in C#

前端 未结 9 1171
逝去的感伤
逝去的感伤 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.

    0 讨论(0)
  • 2020-12-16 10:29

    The first sentence of the MSDN documentation answers your question:

    The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.

    http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx

    0 讨论(0)
  • 2020-12-16 10:37

    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;).

    0 讨论(0)
  • 2020-12-16 10:38

    No. fields can not be virtual\abstract but properties can.

    0 讨论(0)
  • 2020-12-16 10:43

    Properties can be virtual, may be you can gain on that. At least it is heavily used in NHibernate.

    Basically you have to have a method to virtualize, how should the virtual field work?

    0 讨论(0)
  • 2020-12-16 10:45

    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.

    0 讨论(0)
提交回复
热议问题