【问题标题】:.NET: Using reflection how can I tell if a property is shadowing another property? [duplicate].NET:使用反射如何判断一个属性是否正在遮蔽另一个属性? [复制]
【发布时间】:2011-07-01 06:38:17
【问题描述】:

可能重复:
How does reflection tell me when a property is hiding an inherited member with the 'new' keyword?

如何使用反射来判断一个属性是否正在遮蔽另一个属性?我正在处理一些代码生成,我需要这些信息来正确调用所述属性。

示例:

class A{
    int Foo {get;set;}
}

class B:A{
    string new Foo {get;set;}
}

我需要生成的代码:

someB.Foo = "";
((A)someB).Foo = 0;

【问题讨论】:

    标签: .net reflection


    【解决方案1】:

    副本中没有任何标记为正确的答案,所以我复制了一个经过轻微更正后似乎可以工作的答案。

        public static bool IsHidingMember(PropertyInfo self)
        {
            Type baseType = self.DeclaringType.BaseType;
            if (baseType == null)
                return false;
    
            PropertyInfo baseProperty = baseType.GetProperty(self.Name);
    
            if (baseProperty == null)
            {
                return false;
            }
    
            if (baseProperty.DeclaringType == self.DeclaringType)
            {
                return false;
            }
    
            var baseMethodDefinition = baseProperty.GetGetMethod().GetBaseDefinition();
            var thisMethodDefinition = self.GetGetMethod().GetBaseDefinition();
    
            return baseMethodDefinition.DeclaringType != thisMethodDefinition.DeclaringType;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多