Get only properties that implement the interface

I have a class that implements an interface. I would like to study only property values ​​that implement my interface.

So let's say, for example, I have this interface:

public interface IFooBar {
    string foo { get; set; }
    string bar { get; set; }
}

And this class:

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

So, I need to execute this without magic lines:

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. 

}

How can I replace this:

if(pi.Name == 'MyOtherPropery1' || pi.Name == 'MyOtherPropery2') 

Instead of checking to find out if my property name is a ==magic string, I just want to check if the property is implemented from my interface.

+5
source share
4 answers

Why use reflection if you know the interface ahead of time? Why not just check if it implements the interface and then discards it?

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

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

, , :

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

, , , .

, , , InterfaceMapping, GetInterfaceMap Type.

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

" , , .

:

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

, :

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
}
+1
0

All Articles