Inherit from struct

前端 未结 7 804
小蘑菇
小蘑菇 2020-12-16 13:07

I am try to figure out what is the problem whit my code. I have this code:

public struct MyStructA
{
    public MyStructA(string str)
    {
        myString=         


        
相关标签:
7条回答
  • 2020-12-16 13:41

    Value types in .NET are weird in that they defined though they are classes derived from a special class called ValueType. For every value type there is a heap object type which behaves like a class object that derives from ValueType, but a value-type storage location holds a collection of bytes which either represents a primitive value, or the concatenation of the bytes necessary to hold all of its public and private fields.

    Since value type storage locations just hold the bytes necessary to represent their values, and hold neither type information nor any reference to an object which would hold type information, the code which uses a value type storage location must know exactly what it is.

    Conventional inheritance requires that objects hold information about their own type, but there is no provision via which value types could do so.

    It would be conceptually possible (and useful) for .NET to allow some limited forms of value-type inheritance with some special rules, such that while a BaseStructure variable could only hold a BaseStructure and couldn't hold a DerivedStructure. One could define a StructureUser<T> where T:BaseStructure, and such class or method could accept any derivative of BaseStructure and use those members--including fields--which were common to the base type.

    Unfortunately, it would be difficult to define rules for generics in such a way as to behave consistently in permitted scenarios and yet not break any existing code.

    For example, within a class Foo<T,U> where T:U it's always possible to store a T to a variable of type U, even if U is a value type (i.e. because value types are sealed, T and U are guaranteed to be the same type). If U could be an inheritable value type and T could be a derivative, such a guarantee would not hold.

    Given the difficulties associated with such inheritance, a more useful alternative would be to provide a safe (even if limited) means via which a property could expose a byref or a const-byref (a byref is the thing which is passed when a parameter uses a ref qualifier).

    Such a feature would remove the unavoidable semantic distinction between fields and properties, and depending upon how it was implemented could offer some major advantages even when used with classes (e.g. it could allow for efficient mixing of immutable and mutable types).

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