仅获取实现接口的属性

Jef*_*ddy 6 c# reflection

我有一个实现接口的类.我只想检查实现我的接口的属性值.

所以,比方说我有这个界面:

public interface IFooBar {
    string foo { get; set; }
    string bar { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

而这堂课:

public class MyClass :IFooBar {
    public string foo { get; set; }
    public string bar { get; set; }
    public int MyOtherPropery1 { get; set; }
    public string MyOtherProperty2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

所以,我需要完成这个,没有神奇的字符串:

var myClassInstance = new MyClass();
foreach (var pi in myClassInstance.GetType().GetProperties()) {
    if(pi.Name == "MyOtherPropery1" || pi.Name == "MyOtherPropery2") {
        continue; //Not interested in these property values
    }
    //We do work here with the values we want. 

}
Run Code Online (Sandbox Code Playgroud)

我该如何替换它:

if(pi.Name == 'MyOtherPropery1' || pi.Name == 'MyOtherPropery2') 
Run Code Online (Sandbox Code Playgroud)

==我不想检查我的属性名称是否是魔术字符串,而是想查看该属性是否是从我的界面实现的.

Pau*_*yng 8

如果您提前了解界面,为什么要使用反射?为什么不测试它是否实现了接口然后转换为那个?

var myClassInstance = new MyClass();
var interfaceImplementation = myClassInstance as IFooBar

if(interfaceImplementation != null)
{
    //implements interface
    interfaceImplementation.foo ...
}
Run Code Online (Sandbox Code Playgroud)

如果您真的必须使用反射,请获取接口类型的属性,因此使用此行来获取属性:

foreach (var pi in typeof(IFooBar).GetProperties()) {
Run Code Online (Sandbox Code Playgroud)

  • 如果对象具有不同的类型,但实现相同的接口,您仍然可以将它们都转换为接口.例如`var a = new List <int>(); var b = new List <string>(); IList c = a; c = b;`将编译并运行. (3认同)