Is it possible to have a virtual/abstract field in a C# class? If so, how is it done?
相关问题
- how to define constructor for Python's new Nam
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
It's possible however to just replace the new field. See this example:
No, a field can only be assigned to not, overridden.
However, you could probably use a property and it would look almost the same
both get used like so:
Unless the consumer is using reflection, it looks exactly the same.
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.
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;
).