开发者

.NET Change the owner of an instance of a class (object) at runtime

开发者 https://www.devze.com 2023-02-02 15:12 出处:网络
Is it possible in .NET C# to change the owner of an object at runtime? For example: class abc { MyClass ClassInstance = new MyClass();

Is it possible in .NET C# to change the owner of an object at runtime?

For example:

class abc {
     MyClass ClassInstance = new MyClass();
     AnotherClass AnotherClassInstance = new AnotherClass();
     // Some how set the owner of "AnotherClassInstance" t开发者_C百科o "ClassInstance"
}

Thanks!


What do you mean by change the owner of an instance? .NET objects don't have owners, so it's really not clear what you want.

If you meant you want the AnotherClass class to always have a MyClass which is considered as its "owner" in the class' logic, then simply add a constructor to AnotherClass which would take a MyClass as a parameter and will keep this reference.

Like this:

public class AnotherClass
{
    MyClass owner = null;

    public AnotherClass(MyClass owner)
    {
        this.owner = owner;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号