How to deal with CS1721 when I really need to inherit from two classes?

狂风中的少年 提交于 2019-12-21 17:53:34

问题


In my C# code I want a CustomIdentity class that inherits from System.MarshalByRefObject and System.Security.Principal.GenericIndentity classes.

However when I try to write such inheritance C# would object with CS1721 error saying I can't directly inherit from more than one class.

Now in this case it's quite easy to overcome this - I'll inherit from IIdentity, add GenericIdentity member variable and reimplement all IIdentity methods via that member variable.

But how would I do in case I wanted to inherit from two classes with a huge set of methods?


回答1:


You don't. You can't.

That is not supported in C# or .NET.

You use multiple interface implementation, and at most single (non-object) inheritance. In most cases, even single inheritance is vastly overused ;p

To absorb the methods, you'd have to use some kind of encapsulation. Extension methods also provide a way to share methods between types, for completeness.




回答2:


Can't inherit from more than one class as you know... really the only way is to do as you say and use interfaces. Or change programming language to one that supports multiple inheritance, but I'm sure that won't help!



来源:https://stackoverflow.com/questions/6503093/how-to-deal-with-cs1721-when-i-really-need-to-inherit-from-two-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!