Inherit from struct

前端 未结 7 938
小蘑菇
小蘑菇 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:26

    There are actually a few good reasons:

    1. Structs have no 'Type'

      ...unless they are 'boxed' into an object.

      An object on the other hand has two "header" fields in the normal CLR where the type is stored (and some GC- and locking info). Adding that would change the size of the structs, and make their size unpredictable (because some runtimes might chose to add that information differently, for example the mono runtime adds more "header" information to its objects than the .net framework runtime, or at least did so in the past)

      This boxing is actually what happens when you try to assign a struct to an interface field it implements. So it would be possible in theory, but then all your structs would be boxed, and that'd be really bad for performance reasons.

    2. Typing and fixed size

      To show why specifically inheriting structs would be a huge problem lets make a simple example.

      Consider two structs: struct MyBaseStruct { public int A; } and a hypothetical struct MyDerivedStruct : MyBaseStruct { public int B; }.

      Now what would happen when I call var array = new MyBaseStruct[10]; ?? How much size would the runtime allocate for that?

      The assignment array[0] = new MyDerivedStruct(); would be troublesome, on 32bit systems it would probably write to the first AND the second slot as well.

      Even if you'd try to "collect" all derived types it wouldn't work, what if you load another dll that defines yet another struct that derives from your base-struct?

    I personally find it pretty important to know the actual issues that probably led the designers to the decision in the first place. But of course a one could also just say "because the designers of the language made it so!" or "because that's what the C# language specification says" :P

提交回复
热议问题