按此字段更改类字段

本文关键字:字段 | 更新日期: 2023-09-27 18:26:41

我有这个代码:

abstract class A
{
    public Master parent;
    public virtual void DoSomething()
}
class Master
{
    public A a;
    public void DoSomething()
    {
        a.DoSomething();
    }
}
class A1 : A
{
    public override void DoSomething()
    {
        parent.a = new A2();
    }
}
class A2 : A
{
    public override void DoSomething()
    {
        parent.a = new A1();
    }
}

我这样做:

Master m = new Master();
m.a = new A1();
m.a.parent = m;
m.DoSomething();

把m.a改成这样好吗?当A1.DoSomething()正在运行时,GarbageCollector能否删除A1对象?当A1将m.a更改为A2时,A1没有参考,所以我不知道它是否安全。

按此字段更改类字段

虚拟方法有主体,否则您必须使用abstract关键字将此方法设置为抽象方法。

 abstract class A
    {
        public Master Parent;
            public virtual void DoSomething()
            {
                //This block is missing in your code
            }
    }

 static void Main(string[] args)
    {
        var m = new Master();
        m.a = new A1 {Parent = m};
        m.DoSomething();
    }

您可能想了解循环引用以及如何去除它们。你不能从硕士班换a有什么原因吗?

abstract class A
{
    public static A GetNextA(AType type)
    {
        switch (type)
        {
            case AType.A1: return new A1();
            case AType.A2: return new A2();
            default: return null;
        }
    }
    public abstract AType DoSomething();
}
class Master
{
    public A a;
    public void DoSomething()
    {
        AType nextAType = a.DoSomething();
        a = A.GetNextA(nextAType);
    }
}
class A1 : A
{
    public override AType DoSomething()
    {
        //do Work
        return AType.A2;
    }
}
class A2 : A
{
    public override AType DoSomething()
    {
        //do Different Work
        return AType.A1;
    }
}
enum AType
{
    A1,
    A2
}

并像一样使用它们

static void Main(string[] args)
{
    var m = new Master();
    m.a = new A1();
    m.DoSomething();
}

我认为它是安全的。当DoSomething()完成时,GC将收集A1的第一个实例。但看起来,您需要在A1中设置A2的父级。DoSomething()