简体   繁体   English

使用反射查找已实现的接口

[英]Using reflection to find interfaces implemented

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? 如果我有一个“用户”对象-如何检查它是否使用反射实现IPerson? To be more precise I have an object that might have a property SomeUser, which should be of some type implementing the interface "IPerson". 更准确地说,我有一个对象,该对象可能具有SomeUser属性,该对象应该是实现接口“ 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...: 我无法弄清楚如何检查属性类型,因为它是“用户”,但是我想检查它是否实现了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...) (请注意,这是我实际情况的简化,但是重点应该是相同的...)

检查Type.IsAssignableFrom方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM