.NET Change the owner of an instance of a class (object) at runtime
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;
}
}
精彩评论