我有一个实现接口的类。我想仅检查实现我的界面的属性值。只获取实现接口的属性
所以,让我们说,例如我有这样的接口:
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')
而不是检查我的属性名称是==
魔术字符串,我想简单地检查,看看是否从我的界面实现属性。
我使用的界面来比较实现接口的两个对象的值,但可能不是同一类型。基本上是两种不同类型之间的平等检查。使用此代码的函数不仅返回相等/不相等,而且返回差异。这就是反思的原因。 –
我的第二个建议是否有帮助,只是迭代接口类型的属性? –
是的,这就是我需要的。一旦接受时间到期,我会尽快接受你的回答。谢谢保罗。 –