简体   繁体   English

C#反射可返回其Type实现特定接口的类中的所有属性

[英]C# reflection to return all properties in a class whose Type implements a specific interface

I am trying to use reflection to return all properties in a class whose Type implements the IMyInterface interface. 我正在尝试使用反射来返回其Type实现IMyInterface接口的类中的所有属性。

Here is a simple console app that shows where I am and isolates the issue at hand... 这是一个简单的控制台应用程序,可显示我的位置并隔离手头的问题...

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var parent = new Parent();

            parent.GetPropertiesThatImplementIMyInterface();
        }
    }

    public interface IMyInterface { }

    public class A : IMyInterface { }

    public class B { }

    public class Parent
    {
        public A A { get; set; }
        public B B { get; set; }

        public void GetPropertiesThatImplementIMyInterface()
        {
            var props = this.GetType().GetProperties().Where(p => p.PropertyType.IsAssignableFrom(typeof(IMyInterface)));

            Debug.WriteLine(props.Count());
        }
    }
}

The Debug.WriteLine returns a count of 0 in the GetPropertiesThatImplementIMyInterface method call. Debug.WriteLineGetPropertiesThatImplementIMyInterface方法调用中返回计数0。 It should return a count of 1 for the A property. 它应该为A属性返回1的计数。 How can this code be changed to make it do what I need? 如何更改此代码以使其满足我的需要?

The docs of Type.IsAssignableFrom says: Type.IsAssignableFrom文档说:

Determines whether an instance of a specified type can be assigned to a variable of the current type. 确定是否可以将指定类型的实例分配给当前类型的变量。

So an expression like 所以像

typeof(A).IsAssignableFrom(typeof(B))

where A and B are reference types, actually checks whether this will compile (without a conversion): 其中AB是引用类型,实际上检查它是否可以编译(无需转换):

A a = someB;

In your case, you want to check whether the property could be assigned to IMyInterface , so: 对于您的情况,您想检查是否可以将属性分配给IMyInterface ,因此:

IMyInterface x = someProperty;

Therefore, you need: 因此,您需要:

typeof(IMyInterface).IsAssignableFrom(p.PropertyType)

Not the other way around. 并非相反。

您是否尝试过反转支票以适合此要求?

typeof(IMyInterface).IsAssignableFrom(p.PropertyType)

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

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