我有一个实现接口(interface)的类。我只想检查实现我的接口(interface)的属性值。
因此,举例来说,我有这个介面:
public interface IFooBar {
string foo { get; set; }
string bar { get; set; }
}
和这个类:
public class MyClass :IFooBar {
public string foo { get; set; }
public string bar { get; set; }
public int MyOtherPropery1 { get; set; }
public string MyOtherProperty2 { get; set; }
}
因此,我需要在没有魔术字符串的情况下完成此操作:
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.
}
我该如何替换:
if(pi.Name == 'MyOtherPropery1' || pi.Name == 'MyOtherPropery2')
与其检查我的属性名称是否为魔术字符串
==
,不如直接检查该属性是否从我的界面实现。 最佳答案
如果您提前知道接口(interface),为什么还要使用反射?为什么不仅仅测试它是否实现了接口(interface),然后强制转换为接口(interface)呢?
var myClassInstance = new MyClass();
var interfaceImplementation = myClassInstance as IFooBar
if(interfaceImplementation != null)
{
//implements interface
interfaceImplementation.foo ...
}
如果确实必须使用反射,请获取接口(interface)类型上的属性,因此请使用此行获取属性:
foreach (var pi in typeof(IFooBar).GetProperties()) {