代码之家  ›  专栏  ›  技术社区  ›  Sammy S

将所有者引用传递给类构造函数

  •  1
  • Sammy S  · 技术社区  · 7 年前

    非常简单的问题: 在c#(Unity)中,我从连接到游戏对象的单行为类创建了一个新的自定义类:

    CustomClass test1 = new CustomClass(t1, t2, 0.5f);
    

    我想让这个类实例知道它的创建者是谁——它是一个协程,应该检查它的父进程是否被破坏。当然我可以这样通过:

    CustomClass test1 = new CustomClass(this, t1, t2, 0.5f);
    ///
    CustomClass(MonoBehaviour creator, string t, string t2, float a);
    

    public static void Test(this MonoBehaviour behaviour, float a);
    ///
    this.Test(0.5f);
    

    对于类构造函数有这样的东西吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Programmer    7 年前

    必须这样做 manually

    您可以使用 static CustomClass MonoBehaviour 每次创建的新实例时 .

    自定义类 单一行为 实例 静止的 词典

    类别:

    public class TestMono: MonoBehaviour
    {
        public static Dictionary<CustomClass, MonoBehaviour> classToMonoBehaviour;
    
        // Use this for initialization
        void Awake()
        {
            classToMonoBehaviour = new Dictionary<CustomClass, MonoBehaviour>();
    
            //Create and add class to the dictionary
            CustomClass cclas = new CustomClass();
            classToMonoBehaviour.Add(cclas, this);
        }
    }
    

    这个 需要访问 创造它的原因:

    public class CustomClass
    {
        public CustomClass(){}
    
        public MonoBehaviour getCreator()
        {
            //Access MonoBehaviour from the dictionary
            MonoBehaviour result;
            TestMono.classToMonoBehaviour.TryGetValue(this, out result);
            return result;
        }
    }