gpt4 book ai didi

c# - 不继承共享属性

转载 作者:太空狗 更新时间:2023-10-30 01:30:40 25 4
gpt4 key购买 nike

我正在使用 Unity 引擎,其中几乎所有脚本的基类都必须派生自 MonoBehaviour。我创建了自己的包装类,它派生自名为 CMonoBehaviour 的 MonoBehaviour,它包含一些我几乎在任何地方都使用的辅助函数。但现在我面临问题,有时我不想从 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
}

最佳答案

您可能想重新考虑您的架构。看来您过度依赖继承来提供功能。

有很多方法可以重组您的方法,例如:

  • 使用扩展方法来提供功能(接口(interface)扩展方法是个好主意)
  • 使用组合
  • 使用接口(interface) + 组合 => 您可以将组合包装在重新实现的属性中,这些属性只会将调用传递给内部对象。

复合/包装解决方案:

    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 设计的核心有一个实体组件系统。过度继承是:

  • 整体设计不佳
  • 与框架作斗争,这是徒劳的

关于c# - 不继承共享属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43899010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com