.NET 在运行时更改类(对象)实例的所有者

Jam*_*mie 0 .net c# runtime class instance

在 .NET C# 中是否可以在运行时更改对象的所有者?

例如:

class abc {
     MyClass ClassInstance = new MyClass();
     AnotherClass AnotherClassInstance = new AnotherClass();
     // Some how set the owner of "AnotherClassInstance" to "ClassInstance"
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ran*_*Ran 5

更改实例的所有者是什么意思?.NET 对象没有owner,所以你真的不清楚你想要什么。

如果您的意思是希望AnotherClass类始终具有MyClass在类的逻辑中被视为其“所有者”的 a,则只需添加一个构造函数,AnotherClass该构造函数将 aMyClass作为参数并保留此引用。

像这样:

public class AnotherClass
{
    MyClass owner = null;

    public AnotherClass(MyClass owner)
    {
        this.owner = owner;
    }
}
Run Code Online (Sandbox Code Playgroud)