c# - 反射(reflect)属性以获取属性。当它们在别处定义时怎么办?

标签 c# reflection attributes instance propertyinfo

我有一个类 Bar 是这样的:

class Foo : IFoo {
  [Range(0,255)]
  public int? FooProp {get; set}
}

class Bar : IFoo
{
  private Foo foo = new Foo();
  public int? FooProp { get { return foo.FooProp; }
                       set { foo.FooProp= value; } } 
}

我需要找到仅反射(reflect)属性 Bar.FooProp 的属性 [Range(0,255)]。我的意思是,当我当前正在解析时, Prop 是在类实例 (.. new Foo()) 中装饰的,而不是在类中。事实上 Bar.FooProp 没有属性

编辑

我在接口(interface)的定义上移动了属性,所以我必须做的是解析继承的接口(interface)以找到它们。我可以这样做,因为 Bar 类必须实现 IFoo。在这种特殊情况下,我很幸运,但是当我没有接口(interface)时问题仍然存在......我下次会注意

foreach(PropertyInfo property in properties)
{
  IList<Type> interfaces = property.ReflectedType.GetInterfaces();
  IList<CustomAttributeData> attrList;
  foreach(Type anInterface in interfaces)
  {
    IList<PropertyInfo> props = anInterface.GetProperties();
    foreach(PropertyInfo prop in props)
    {
      if(prop.Name.Equals(property.Name))
      { 
        attrList = CustomAttributeData.GetCustomAttributes(prop);
        attributes = new StringBuilder();
        foreach(CustomAttributeData attrData in attrList)
        {
            attributes.AppendFormat(ATTR_FORMAT,
                                        GetCustomAttributeFromType(prop));
        }
      }
    }
  }

最佳答案

前一段时间我遇到过类似的情况,我在接口(interface)的方法上声明了一个属性,我想从实现该接口(interface)的类型的方法中获取该属性。例如:

interface I {
  [MyAttribute]
  void Method( );
}

class C : I {
  void Method( ) { }
}

下面的代码用于检查类型实现的所有接口(interface),查看给定的方法实现了哪些接口(interface)成员(使用GetInterfaceMap),并返回任何属性在那些成员上。在此之前,我还检查方法本身是否存在该属性。

IEnumerable<MyAttribute> interfaceAttributes =
  from i in method.DeclaringType.GetInterfaces( )
  let map = method.DeclaringType.GetInterfaceMap( i )
  let index = GetMethodIndex( map.TargetMethods, method )
  where index >= 0
  let interfaceMethod = map.InterfaceMethods[index]
  from attribute in interfaceMethod.GetCustomAttributes<MyAttribute>( true )
  select attribute;

...

static int GetMethodIndex( MethodInfo[] targetMethods, MethodInfo method ) {
  return targetMethods.IndexOf( target =>
         target.Name == method.Name
      && target.DeclaringType == method.DeclaringType
      && target.ReturnType == method.ReturnType
      && target.GetParameters( ).SequenceEqual( method.GetParameters( ), PIC )
  );
}

关于c# - 反射(reflect)属性以获取属性。当它们在别处定义时怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1021447/

相关文章:

c# - 多页形式。我在哪里保存以前的数据?

c# - 同一进程中的多个应用程序使用具有不同目标的 NLog

c# - 从函数中提取函数名

c# - 线程 : incorrect Variable passing C#

c# - 使用EF4仅获得SQL表的最后一行的最有效方法是什么?

dictionary - Go中通过反射为struct成员赋值

.net - 在 IMetadataImport 或 MonoCecil 中,如何确定内部类中的方法是否可以从其他程序集访问?

javascript - jQuery - 数组元素作为选择器

ruby-on-rails-3 - 导轨 3 : Why does my image_tag automatically add inline style attributes to the HTML making it invisible?

python - 我可以获取类的 __init__ 方法中定义的所有属性吗?