Is it safe for structs to implement interfaces?

前端 未结 9 2103
既然无缘
既然无缘 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条回答
  •  日久生厌
    2020-11-29 17:18

    There is very little reason for a value type to implement an interface. Since you cannot subclass a value type, you can always refer to it as its concrete type.

    Unless of course, you have multiple structs all implementing the same interface, it might be marginally useful then, but at that point I'd recommend using a class and doing it right.

    Of course, by implementing an interface, you are boxing the struct, so it now sits on the heap, and you won't be able to pass it by value anymore...This really reinforces my opinion that you should just use a class in this situation.

提交回复
热议问题