【问题标题】:Unity C# Singleton + non-singleton class both extending to the same parent classUnity C# Singleton + non-singleton 类都扩展为同一个父类
【发布时间】:2021-07-23 05:33:13
【问题描述】:

假设我有 ChildA 和 ChildB 类,它们都扩展到类 Parent。应该只有一个 ChildA 实例和多个 ChildB 实例。它们都扩展到 Parent 的原因是因为它们的一些变量和方法是相同的。解决这个问题的最佳方法是什么?我曾尝试将 Singleton 用于 ChildA,但因为它需要静态字段/方法,它似乎与其父类冲突。删除 ChildA 的父类可以解决这个问题,但它似乎不对,因为它的某些方法和变量与 ChildB 的匹配。任何帮助将不胜感激。

【问题讨论】:

  • 为什么要使用单例?如果我理解正确,您应该使用继承:(

标签: c# class unity3d inheritance singleton


【解决方案1】:

你得到的错误\冲突到底是什么?

已尝试以下代码没有问题:

using System;

public class Parent
{
    protected int value;
}

public class ChildA: Parent
{
    public static ChildA self = null;
    
    public ChildA()
    {
        if (self == null)
            self = this;
        
        value = 10;
    }
    public int GetVal()
    {
        return(value);
    }
}

public class ChildB: Parent
{
    public ChildB()
    {
        value = 20;
    }
    public int GetVal()
    {
        return(value);
    }
}


public class Program
{
    public static void Main()
    {
        new ChildA();
        ChildB obj = new ChildB();
        
        Console.WriteLine("Value of Singleton ChildA: " + ChildA.self.GetVal());
        Console.WriteLine("Value of ChildB: " + obj.GetVal());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多