C#反射返回其类型实现特定接口的类中的所有属性
我试图使用反射返回一个类中的所有属性,该类的类型实现了C#反射返回其类型实现特定接口的类中的所有属性,c#,C#,我试图使用反射返回一个类中的所有属性,该类的类型实现了IMyInterface接口 这里是一个简单的控制台应用程序,显示我在哪里,并找出手头的问题 namespace ConsoleApp1 { class Program { static void Main(string[] args) { var parent = new Parent(); parent.GetPropertiesThatIm
IMyInterface
接口
这里是一个简单的控制台应用程序,显示我在哪里,并找出手头的问题
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());
}
}
}
Debug.WriteLine
在GetPropertiesThatImplementIMyInterface
方法调用中返回0的计数。对于a
属性,它应该返回1的计数。如何更改此代码以使其满足我的需要?您是否尝试过通过反转支票来满足此要求
typeof(IMyInterface).IsAssignableFrom(p.PropertyType)
类型的IsAssignableFrom表示:
确定是否可以将指定类型的实例分配给当前类型的变量
所以一个表达像
typeof(A).IsAssignableFrom(typeof(B))
如果A
和B
是引用类型,则实际检查是否会编译(无转换):
在您的情况下,您希望检查属性是否可以分配给IMyInterface
,因此:
IMyInterface x = someProperty;
因此,您需要:
typeof(IMyInterface).IsAssignableFrom(p.PropertyType)
而不是相反。我想你把它倒过来了<代码>类型(IMyInterface)。可从(p.PropertyType)
中识别?是的,就是这样,谢谢!我多么希望这个方法被称为其他方法。也许只有我一个人,但这让我头脑混乱,我不知道他们的顺序。最后我总是写一个测试。我应该创建一个DotNetFiddle或一个自我回答的问题,并保存一个指向它的链接。@ScottHannen我同意,这是一个非常不直观的功能。我认为创建一个扩展方法IsAssignableTo
并使用它会有所帮助。Autofac提供了这样一个功能。
typeof(IMyInterface).IsAssignableFrom(p.PropertyType)