gpt4 book ai didi

C# 反射以匹配 Type List where T IsSubClass(Foo)

转载 作者:行者123 更新时间:2023-11-30 20:57:14 24 4
gpt4 key购买 nike

我有一个包含 List<T> 属性的类.其中一些属性,T 属于从类继承的类,例如 Foo。

public class Foo {}
public class MyTypeA : Foo {}
public class MyTypeB : Foo {}

// Not : Foo
public class MyTypeC {}

public class Bar
{
// I can Match these
public MyTypeA PropA { get; set; }
public MyTypeB PropB { get; set; }

// How can I match these based on IsSubclassOf(Foo)
public List<MyTypeA> PropListA { get; set; }
public List<MyTypeB> PropListB { get; set; }

// Do not match the props below
public MyTypeC PropC { get; set; }
public List<MyTypeC> PropListC { get; set; }
public List<string> PropListString { get; set; }

}

我已经成功匹配了属于 Foo 子类的属性如下所示。

foreach (var oProp in T.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
// Find Prop : Foo
if( oProp.PropertyType.IsSubclassOf( typeof(Foo) ) )
{
// Add Property to dictionary
aPropInheritType.Add(
oProp.Name,
oProp
);
}

// Match List<T> where T : Foo
// How do I test for Generic List that's Type T is a subclass
// of the class Foo ?

}

我看到类型类有许多通用属性,但无法获取通用列表的类型,然后根据 IsSubclassOf(Foo) 进行测试。

最佳答案

测试一个属性是否有返回类型List<T> ,使用下一个代码:

Type returnType = oProp.PropertyType;
if(returnType.IsGenericType &&
returnType.GetGenericTypeDefinition() == typeof(List<>) &&
typeof(Foo).IsAssignableFrom(returnType.GetGenericArguments()[0]))
{
//property is of type List<T>, where T is derived from Foo
}

关于C# 反射以匹配 Type List<T> where T IsSubClass(Foo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16981070/

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