如何在运行时访问派生类字段?

问题描述 投票:0回答:1

大家好,有没有办法在派生类的基类中实现Equals方法,因为比较字段只存在于派生类中:

    public abstract partial class Primitive {
                public abstract PrimitiveKind PrimitiveKind { get; }
public static Primitive CreateEmpty(PrimitiveKind primitiveKind) {
                switch (primitiveKind) {
                    case PrimitiveKind.Bool: return new Bool();
                    case PrimitiveKind.String: return new String();
                    case PrimitiveKind.Char: return new Char();

                    case PrimitiveKind.Sbyte: return new Sbyte();
                    case PrimitiveKind.Byte: return new Byte();
                    case PrimitiveKind.Short: return new Short();
                    case PrimitiveKind.Ushort: return new Ushort();
                    case PrimitiveKind.Int: return new Int();
                    case PrimitiveKind.Uint: return new Uint();
                    case PrimitiveKind.Long: return new Long();
                    case PrimitiveKind.Ulong: return new Ulong();


                    case PrimitiveKind.Float: return new Float();
                    case PrimitiveKind.Double: return new Double();
                    case PrimitiveKind.Decimal: return new Decimal();
                    default:
                        throw new NotImplementedException();
                }
            }
    }

每个Derived类型都是这样的:

 public sealed class Bool : Primitive {

                    public bool Value { get; set; }
                    public override PrimitiveKind PrimitiveKind => PrimitiveKind.Bool;
            }
public sealed class Byte : Primitive {

                public byte Value { get; set; }
                public override PrimitiveKind PrimitiveKind => PrimitiveKind.Byte;
            }

我希望Primitive类型重写Equals方法,以便它在运行时比较Value字段。我需要在此处完成相同的测试目的。

就像是 :

class Primitive{
    public bool override Equals<T>(T other)
    {
    return  `(T)((dynamic)this.[Value])` .Equals(other.Value);
    }

基类中不存在值 - 无论如何我可以“假装”它在运行时存在吗?dynamic这个词是关键吗? (我对它的用法不太熟悉)}

用法:

Primitive a=new Bool();
Primitive b=new Bool();
Assert.AreEqual(a,b);
c# dynamic polymorphism runtime
1个回答
2
投票

您可以创建一个受保护的抽象属性,您的类必须实现:

public abstract partial class Primitive
{
    protected abstract object ValueObject { get; }
    public override bool Equals(object obj)
    {
        return obj is Primitive p ? this.ValueObject.Equals(p.ValueObject) : false;
    }
    ...
}

public sealed class Bool : Primitive
{
    protected override object ValueObject => this.Value;
    public bool Value { get; set; }
    public override PrimitiveKind PrimitiveKind => PrimitiveKind.Bool;
}

获取ValueObject时,此解决方案会导致值被加框,但它仍然可能比dynamic更快,并且实现样板不是很高。

© www.soinside.com 2019 - 2024. All rights reserved.