2009-06-20 23 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) 
); 
} 
相關問題