如何使用反射来查找实现特定接口的属性? [英] How can I use reflection to find the properties which implement a specific interface?

查看:147
本文介绍了如何使用反射来查找实现特定接口的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:

public interface IAnimal
{
}

public class Cat: IAnimal
{
}

public class DoStuff
{
    private Object catList = new List<Cat>();

    public void Go()
    {
        // I want to do this, but using reflection instead:
        if (catList is IEnumerable<IAnimal>)
            MessageBox.Show("animal list found");

        // now to try and do the above using reflection...
        PropertyInfo[] properties = this.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            //... what do I do here?
            // if (*something*)
                MessageBox.Show("animal list found");
        }
    }
}

你能否完成if语句用正确的代码替换某些东西

Can you complete the if statement, replacing something with the correct code?

编辑:

我注意到我应该使用一个属性而不是一个字段才能工作,所以它应该是:

I noticed that I should have used a property instead of a field for this to work, so it should be:

    public Object catList
    {
        get
        {
          return new List<Cat>();
        }
    }


推荐答案

你可以查看属性' PropertyType ,然后使用 IsAssignableFrom ,我认为这是你想要的:

You can look at the properties' PropertyType, then use IsAssignableFrom, which I assume is what you want:

PropertyInfo[] properties = this.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
    if (typeof(IEnumerable<IAnimal>).IsAssignableFrom(property.PropertyType))
    {
        // Found a property that is an IEnumerable<IAnimal>
    }                           
}

当然,您需要为您的房产添加房产class,如果你想让上面的代码工作; - )

Of course, you need to add a property to your class if you want the above code to work ;-)

这篇关于如何使用反射来查找实现特定接口的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆