2009-06-20 24 views
4

我有一个类酒吧这样的:反映属性以获取属性。如何在别处定义它们时执行操作?

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; } } 
} 

我需要找到属性[范围(0,255)仅反映在财产Bar.FooProp。我的意思是,当我正在解析时,prop是在类实例(.. new Foo())中进行装饰的,而不是在类中。逸岸Bar.FooProp没有属性

编辑

我感动的接口的定义的属性,所以我要做的就是解析继承的接口来找到它们。我能做到这一点,因为酒吧类必须实现IFoo.In这种特殊情况下,我很幸运,但问题仍然存在,当我有没有接口...我会留意下一次

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)); 
     } 
     } 
    } 
    } 

回答

1

看时在FooProp,没有什么可以识别Foo(在任何时候)的存在。也许你可以添加一个属性来识别foo字段,并反思(通过FieldInfo.FieldType)?

+0

事实上,关键在于反映“内部”get/set方法。我不知道是否有一种方法可以理解返回参数是对实例方法的调用。 – 2009-06-20 11:46:35

+1

如果您*内* get/set,那么您已经知道类型...只使用已知类型... ? – 2009-06-20 11:57:17

2

我曾经有过类似的情况,我在接口中的某个方法中声明了一个属性,并且我想从实现该接口的类型的方法获取该属性。例如:

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

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

下面的代码是用于检查所有由类型实现的接口的,看哪个接口部件给定method工具(使用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) 
); 
} 
相关问题