Is it safe for structs to implement interfaces?

前端 未结 9 2099
既然无缘
既然无缘 2020-11-29 16:44

I seem to remember reading something about how it is bad for structs to implement interfaces in CLR via C#, but I can\'t seem to find anything about it. Is it bad? Are the

9条回答
  •  萌比男神i
    2020-11-29 17:00

    Structs are implemented as value types and classes are reference types. If you have a variable of type Foo, and you store an instance of Fubar in it, it will "Box it" up into a reference type, thus defeating the advantage of using a struct in the first place.

    The only reason I see to use a struct instead of a class is because it will be a value type and not a reference type, but the struct can't inherit from a class. If you have the struct inherit an interface, and you pass around interfaces, you lose that value type nature of the struct. Might as well just make it a class if you need interfaces.

提交回复
热议问题