2010-02-24 49 views
2

如何從我的類實現的接口方法檢索屬性?從接口方法檢索屬性

編輯:我不知道當時的接口,只有類的類型,或該類的一個實例。

編輯:添加了繼承標誌的屬性,但它沒有效果。

[TestFixture] 
public class MyTests { 
    [Test] 
    public void shouldGetMyAttribute() { 
     var type = typeof (MyClass); 
     var method = type.GetMethod("MyMethod"); 
     var attributes = method.GetCustomAttributes(true); 
     var myAttribute = attributes.SingleOrDefault(x => x is MyAttributeAttribute); 
     Assert.That(myAttribute, Is.Not.Null); 
    } 
} 

public class MyClass : IMyInterface { 
    public void MyMethod() { 
     throw new NotImplementedException(); 
    } 
} 

public interface IMyInterface { 
    [MyAttribute] 
    void MyMethod(); 
} 

[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 
public class MyAttributeAttribute : Attribute {} 
+1

相關:http://stackoverflow.com/questions/1123563/are-method-attributes-inherited-in-c – 2010-02-24 21:59:20

+0

發現這說明它的錯誤,但我不知道如果這是正確的仍然。它從'05 .. http://bytes.com/topic/c-sharp/answers/232588-interface-properties-custom-attributes – MatteS 2010-02-24 22:17:23

+0

仍試圖想出一個解決方法。我想我必須使用GetInterfaceMap方法使用稱爲InterfaceMapping的東西,但還是很想弄明白。 – MatteS 2010-03-03 20:41:21

回答

2

typeof(MyClass).GetInterfaces()將返回該類實現的所有接口。從那裏你可以使用類似於Ben M發佈的代碼來導航到正確的方法和屬性。

+0

請在代碼中描述。從我能收集到的信息來看,並不那麼容易。我如何匹配該方法?我不能按名稱匹配或使用Equals。我想我必須使用GetInterfaceMap方法使用稱爲InterfaceMapping的東西,但還是很想弄明白... – MatteS 2010-03-03 20:39:05