Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to find interfaces implemented

Tags:

I have the following case:

public interface IPerson { .. }     public class Person : IPerson { .. }     public class User : Person { .. } 

Now; if I have a "User" object - how can I check if this implements IPerson using reflection? To be more precise I have an object that might have a property SomeUser, which should be of some type implementing the interface "IPerson". In my case I actually have a User, but this is what I want to check through reflection. I can't figure out how to check the property type since it is a "User", but I want to check if it implements IPerson...:

var control = _container.Resolve(objType); // objType is User here var prop = viewType.GetProperty("SomeUser"); if ((prop != null) && (prop.PropertyType is IPerson))  { .. } 

(Note that this is a simplification of my actual case, but the point should be the same...)

like image 373
stiank81 Avatar asked Oct 05 '09 11:10

stiank81


People also ask

What is System reflection used for?

Reflection Namespace. Contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata. These types also can be used to manipulate instances of loaded types, for example to hook up events or to invoke methods.

What is the use of reflection API in .NET framework?

Reflection provides objects that encapsulate assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object. You can then invoke the type's methods or access its fields and properties.

Is reflection API slow?

Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations. If you use it 10'000 times in a time-critical method, I would consider to change the implementation.

What is reflection where can it be used C#?

Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically -- you can retrieve information on the loaded assemblies and the types defined in them.


2 Answers

Check the Type.IsAssignableFrom method.

like image 162
Konamiman Avatar answered Oct 05 '22 03:10

Konamiman


var control = _container.Resolve(objType);  var prop = viewType.GetProperty("SomeUser"); if ((prop != null) && (prop.PropertyType.GetInterfaces().Contains(typeof(IPerson)))  { .. } 
like image 33
Stefan Steinegger Avatar answered Oct 05 '22 04:10

Stefan Steinegger