从子类访问父属性名称

时间:2017-09-02 13:42:16

标签: c# oop reflection

我有一个类:

class A {
    public B prop1 {get; set;}
    public B prop2 {get; set;}
}

class B {
    public B {
        // which name of my parent property - prop1 or prop2?
    }
}

如何从B类的构造函数中找出这个B类实例的父类(prop1或prop2)的哪些属性的值?

1 个答案:

答案 0 :(得分:0)

在构造函数中,如果类B的实例将根本不与A关联。 prop1或prop2的赋值只能在构造函数完成后发生。

如果没有B到A的直接引用,B就无法知道它与哪个属性相关。如果B有对A的引用,它可以检查A的每个属性并查看哪个等于它,但这不是一个特别漂亮的解决方案。

您可以使用的另一个策略是在A的属性中做一些工作,以通过prop1或prop2将B的实例标记为属于A.在下面的实现中,我使用CallerMemberName以便不将名称作为字符串传递,编译器将在调用方法时将其传递给我们

class A
{
    private B _prop1;
    public B prop1
    {
        get => _prop1;
        set => SetProp(value, ref _prop1);
    }

    private B _prop2;
    public B prop2
    {
        get => _prop2;
        set => SetProp(value, ref _prop2);
    }

    private void SetProp(B value, ref B field, [CallerMemberName] string propName = null)
    {
        if(field != null) field.Association = null;
        field = value;
        if (field != null) field.Association = propName;
    }

}

class B
{
    public string Association { get; set; }
}
相关问题