2011-11-15 76 views
5

我有一个实现接口的类。我想仅检查实现我的界面的属性值。只获取实现接口的属性

所以,让我们说,例如我有这样的接口:

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') 

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

回答

8

为什么使用反射提前知道接口?为什么不只是测试它是否实现了接口然后转换为接口呢?

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

if(interfaceImplementation != null) 
{ 
    //implements interface 
    interfaceImplementation.foo ... 
} 

如果你真的必须使用反射,得到的接口类型的属性,所以用这条线来获得属性:

foreach (var pi in typeof(IFooBar).GetProperties()) { 
+0

我使用的界面来比较实现接口的两个对象的值,但可能不是同一类型。基本上是两种不同类型之间的平等检查。使用此代码的函数不仅返回相等/不相等,而且返回差异。这就是反思的原因。 –

+0

我的第二个建议是否有帮助,只是迭代接口类型的属性? –

+0

是的,这就是我需要的。一旦接受时间到期,我会尽快接受你的回答。谢谢保罗。 –

1

也许有继发接口:

public interface IFooAlso { 
    int MyOtherProperty1 { get; set; } 
    string MyOtherProperty2 { get; set; } 
} 

添加第二个接口:

public class MyClass :IFooBar, IFooAlso { 
    public string foo { get; set; } 
    public string bar { get; set; } 
    public int MyOtherPropery1 { get; set; } 
    public string MyOtherProperty2 { get; set; } 
} 

和测试它像这样:

var myClassInstance = new MyClass(); 

if(myClassInstance is IFooAlso) { 
    // Use it 
} 
3

我倾向于同意,就像Paul T.所建议的那样,它看起来像要投射到界面上。

然而,您所询问的信息可在InterfaceMapping类型中获得,可从Type实例的GetInterfaceMap方法获得。从

http://msdn.microsoft.com/en-us/library/4fdhse6f(v=VS.100).aspx

“的接口映射表示接口被如何映射到上实现该接口的类的实际方法”。

例如:

var map = typeof(int).GetInterfaceMap(typeof(IComparable<int>));