2010-02-24 59 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