[英]C# creating a class derived from an abstract and singleton class
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
// this is my singleton class
}
public abstract class A : Singleton<A>
{
// this is my base abstract class.
}
public B : A
{
// I want this class to be derived from A, also to derive from Singleton and MonoBehaviour
}``
Since c# does not support multiple inheritance. 由于c#不支持多重继承。 I am trying to make a class which is derived from class A and singleton class. 我试图做一个从A类和单例类派生的类。 When I call an instance of B. It creates an instance of A and that gives a null exception. 当我调用B的实例时。它将创建A的实例,并给出一个空异常。 Is there a solution for this or do I have to use interface ? 是否有解决方案,还是必须使用接口? Thanks in advance. 提前致谢。
The first question is : What do you want to share between this classes ? 第一个问题是 :您想在这些课程之间分享什么?
Waiting this answer, I will try to give you a generic explanation with as much detail as possible. 等待这个答案,我将尝试为您提供尽可能详尽的一般解释。
1 - Sharing only methods 1-仅共享方法
If you want to share only methods, the best practice is to use Interfaces to split your logic as you want and give it to concrete classes : 如果您只想共享方法,则最佳实践是使用接口根据需要拆分逻辑并将其提供给具体的类:
public interface IInterface1{
//some methods
}
public interface IInterface2{
//some methods
}
public class MyClass : IInterface1, IInterface2{
}
MyClass can be abstract if you want and you can put some methods as virtual to override them if you want too 如果需要, MyClass可以是抽象的,也可以将某些方法虚拟化以覆盖它们
2 - Sharing methods and properties 2-共享方法和属性
You will do it from the same way, but the Interfaces need to be added to the correct class 您将以相同的方式进行操作,但是需要将接口添加到正确的类中
public interface IInterface1{
//some methods
}
public interface IInterface2{
//some methods
}
public abstract class MyAbstractClass {
//some methods and properties
}
public class MyClass : MyAbstractClass, IInterface1, IInterface2{
}
You can add the interfaces to MyAbstractClass instead of MyClass , it depends your architecture and your needs 您可以将接口添加到MyAbstractClass而不是MyClass ,这取决于您的体系结构和需求
3 - Singleton 3-单身人士
For the singleton, as say in the comments, this is only a way to gain global accessibility, so you need to do it in your "last" class, here MyClass 对于单例,如评论中所述,这只是获得全局可访问性的一种方法,因此您需要在“最后一个”类中进行此操作,此处为MyClass
I Hope I expressed myselft enought correctly for this explanation and I hope this answer will help you. 希望我正确表达自己的意思,并希望这个答案对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.