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

发布于 2024-10-10 06:48:02 字数 278 浏览 0 评论 0原文

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

例如:

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

谢谢!

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" to "ClassInstance"
}

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光无声 2024-10-17 06:48:02

更改实例的所有者是什么意思? .NET 对象没有所有者,因此并不清楚您想要什么。

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

像这样:

public class AnotherClass
{
    MyClass owner = null;

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

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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文