如何使用反射来查找实现特定接口的属性?

Ste*_*uer 13 .net c# reflection interface

考虑这个例子:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你能完成if语句,用正确的代码替换一些东西吗?

编辑:

我注意到我应该使用属性而不是字段来实现这一点,所以它应该是:

    public Object catList
    {
        get
        {
          return new List<Cat>();
        }
    }
Run Code Online (Sandbox Code Playgroud)

dri*_*iis 15

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

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>
    }                           
}
Run Code Online (Sandbox Code Playgroud)

当然,如果你想让上面的代码工作,你需要为你的类添加一个属性;-)

  • 我不认为这会起作用 - 不应该是`if((typeof(IEnumerable <IAnimal>).IsAssignableFrom(property.PropertyType))`?? (3认同)
  • 问题可能是您将值键入为对象 - 您可以将任何内容分配给对象.因此,如果您想保留它,您可能需要查看属性的运行时值,假设您有一个值. (2认同)