gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:28:05 36 4
gpt4 key购买 nike

我正在尝试使用反射返回一个类中的所有属性,该类的类型实现了 IMyInterface 接口(interface)。

这是一个简单的控制台应用程序,可以显示我所在的位置并隔离手头的问题...

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.WriteLineGetPropertiesThatImplementIMyInterface 方法调用中返回计数 0。它应该为 A 属性返回计数 1。如何更改此代码以使其执行我需要的操作?

最佳答案

docs Type.IsAssignableFrom 说:

Determines whether an instance of a specified type can be assigned to a variable of the current type.

所以像这样的表达式

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

其中 AB 是引用类型,实际上检查这是否会编译(没有转换):

A a = someB;

在你的例子中,你想检查属性是否可以分配给 IMyInterface,所以:

IMyInterface x = someProperty;

因此,您需要:

typeof(IMyInterface).IsAssignableFrom(p.PropertyType)

反之则不然。

关于C#反射返回其Type实现特定接口(interface)的类中的所有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56837757/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com