我正在使用引擎Unity,几乎所有脚本的基类都必须从MonoBehaviour派生.我创建了自己的包装类,它来自MonoBehaviour,名为CMonoBehaviour,它包含了我几乎无处不在的一些辅助函数.但是现在我面临的问题是,有时我不想从MonoBehavuour派生出来但是ThirtPartyLibraryWrapperClass(类,也是从MonoBehaviour派生出来的,但也实现了一些附加的功能 – 就像我的包装一样).这是我想要存档的示例.
编辑:我忘了提到ThirtPartyLibraryWrapperClass是用dll打包的,这意味着我无法以任何方式修改它
// This is what I have
public class CMonoBehavour : MonoBehaviour
{
public int SomeHelperProperty1 { get; private set; }
public int SomeHelperProperty2 { get; private set; }
public int SomeHelperProperty3 { get; private set; }
public int SomeHelperProperty4 { get; private set; }
}
public class ThirtPartyLibraryWrapperClass : MonoBehaviour
{
public int SomeHelperProperty5 { get; private set; }
public int SomeHelperProperty6 { get; private set; }
}
// My problem :
public class ExampleUseage1 : CMonoBehavour
{
// here I have to copypaste content of ThirtPartyLibraryWrapperClass because I cust cannot derive from two classes
}
public class ExampleUseage2 : ThirtPartyLibraryWrapperClass
{
// here I have to copypaste content of CMonoBehavour because I cust cannot derive from two classes
}
解决方法:
您可能想重新考虑您的架构.
您似乎过度依赖继承来提供功能.
有很多方法可以重构您的方法,例如:
>使用扩展方法提供功能(界面扩展方法是个好主意)
>使用成分
> use interfaces composition =>您可以将组合包装在重新实现的属性中,这些属性只会将调用传递给内部对象.
复合/包装解决方案:
public class CMonoBehavour : MonoBehaviour
{
public int SomeHelperProperty1 { get; private set; }
public int SomeHelperProperty2 { get; private set; }
public int SomeHelperProperty3 { get; private set; }
public int SomeHelperProperty4 { get; private set; }
}
public class ThirtPartyLibraryWrapperClass : MonoBehaviour
{
public int SomeHelperProperty5 { get; private set; }
public int SomeHelperProperty6 { get; private set; }
}
//COMPOSITE SOLUTION
public class CompositeMonoBehaviour : CMonoBehaviour
{
private ThirtPartyLibraryWrapperClass _thirdParty;
public int SomeHelperProperty5 { get{ return _thirdParty.SomeHelperProperty5; } }
public int SomeHelperProperty6 { get{ return _thirdParty.SomeHelperProperty6; } }
}
public class ExampleUseage1 : CompositeMonoBehaviour
{
//you have all your properties, great news!
}
public class ExampleUseage2 : CompositeMonoBehaviour
{
//you have all your properties, great news!
}
请记住,Unity的实体组件系统是GameObject设计的核心.过度继承是:
>一般的糟糕设计
>打击框架,这是一种徒劳的做法
原文地址:https://codeday.me/bug/20190627/1307386.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。