开发者

Virtual/Abstract fields in C#

Is it possible to have a virtual/abstract field in 开发者_如何学Goa C# class? If so, how is it done?


A Virtual/Abstract field? No. Fields are just there to hold data. There's nothing to implement.

You can define a Virtual/Abstract Property though.


You can however have virtual or abstract properties:

public abstract string ModelName { get; set; }


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.


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


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


No. You'd have to use a property to accomplish what you seem to what to do.


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜