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 {}
相關:http://stackoverflow.com/questions/1123563/are-method-attributes-inherited-in-c – 2010-02-24 21:59:20
發現這說明它的錯誤,但我不知道如果這是正確的仍然。它從'05 .. http://bytes.com/topic/c-sharp/answers/232588-interface-properties-custom-attributes – MatteS 2010-02-24 22:17:23
仍試圖想出一個解決方法。我想我必須使用GetInterfaceMap方法使用稱爲InterfaceMapping的東西,但還是很想弄明白。 – MatteS 2010-03-03 20:41:21