使用反射查找实现的接口

时间:2022-09-25 12:10:57

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...:

现在;如果我有一个“User”对象——如何检查它是否使用反射实现IPerson ?更准确地说,我有一个对象,它可能有一个属性SomeUser,它应该是某种实现接口“IPerson”的类型。在我的例子中,我实际上有一个用户,但这是我想通过反射来检查的。我不知道如何检查属性类型,因为它是一个“用户”,但是我想检查它是否实现了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...)

(请注意,这是对我的实际情况的简化,但要点应该是相同的……)

3 个解决方案

#1


29  

Check the Type.IsAssignableFrom method.

检查类型。IsAssignableFrom方法。

#2


13  

var control = _container.Resolve(objType); 
var prop = viewType.GetProperty("SomeUser");
if ((prop != null) && (prop.PropertyType.GetInterfaces().Contains(typeof(IPerson))) 
{ .. }

#3


0  

See Implementations of interface through Reflection.

通过反射查看接口的实现。

#1


29  

Check the Type.IsAssignableFrom method.

检查类型。IsAssignableFrom方法。

#2


13  

var control = _container.Resolve(objType); 
var prop = viewType.GetProperty("SomeUser");
if ((prop != null) && (prop.PropertyType.GetInterfaces().Contains(typeof(IPerson))) 
{ .. }

#3


0  

See Implementations of interface through Reflection.

通过反射查看接口的实现。

相关文章