gpt4 book ai didi

c# - 如何识别通用声明类型?

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

假设您有 IList 或 List 作为属性。你怎么知道它是一个列表,还是一个 IList?不依靠反复试验可以做到这一点吗?

类型的名称类似于 List`1。考虑字符串破解是否合理?

class Program {

public class Class1 {
public int a { get; set; }

public IList<int> list { get; set; }


public List<int> concreteList { get; set; }
}

static void Main(string[] args)
{
Test1();
Test2();
}

private static void Test1()
{
var t = typeof (Class1);
var p = t.GetProperty("list");

if (p.PropertyType.IsInterface && p.PropertyType.IsGenericType)
{
var ps = p.PropertyType.GetGenericArguments();
var underlying = p.PropertyType.GetInterface("IList");

var b = underlying == typeof (IList<>);

}
}

private static void Test2() {
var t = typeof(Class1);
var p = t.GetProperty("concreteList");

if (!p.PropertyType.IsInterface && p.PropertyType.IsGenericType) {
var ps = p.PropertyType.GetGenericArguments();

var underlying3 = p.PropertyType.GetGenericTypeDefinition();

var b = underlying3 == typeof (List<>);
}
}
}

最佳答案

如果您可以获得属性值,那么对其类型的测试就可以非常简单(请参阅 Guffa 的回答)。但是,如果您想在不调用该属性的情况下找到它,那么您的代码几乎就在那里 - 例如,

var t = p.PropertyType;
if (t.IsGenericType && !t.IsGenericTypeDefinition && !t.IsInterface && !t.IsValueType)
{
// we are dealing with closed generic classes
var typeToTest = typeof (List<>);
var tToCheck = t.GetGenericTypeDefinition();
while (tToCheck != typeof(object))
{
if (tToCheck == typeToTest)
{
// the given type is indeed derived from List<T>
break;
}
tToCheck = toCheck.BaseType;
}
}

IsGenericType指示该类型是通用的 - 可以是开放的 ( List<T> ) 或封闭的 ( List<int> )。 IsGenericTypeDefinition指示泛型类型是否为开放类型。 GetGenericTypeDefinition在封闭/开放通用类型上将返回通用定义(即开放通用类型)。

关于c# - 如何识别通用声明类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10027669/

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