C# 获取类型() : Code how to get the type of T in List<T> without actual elements?

标签 c# reflection

<分区>

如果我这样做:

var a = new List<something>();
var b = new something();
a.Add(b);
var c = a[0].GetType();

C 包含我想要的类型(即“某物”)。在不创建列表的情况下如何获得“某物”的类型?

最佳答案

在这种情况下,您可以说 var c = typeof(something);但在一般情况下你可以使用这个:

Type c = a.GetType().GetGenericArguments()[0];

更具体地说,可能有 4 种不同的情况:

void func1(List<something> arg)
{
    Type t = typeof(something);
}

void func2<T>(List<T> arg)
{
    Type t = typeof(T);
}

void func3(object arg)
{
    // assuming arg is a List<T>
    Type t = arg.GetType().GetGenericArguments()[0];
}

void func4(object arg)
{
    // assuming arg is an IList<T>
    Type t;

    // this assumes that arg implements exactly 1 IList<> interface;
    // if not it throws an exception indicating that IList<> is ambiguous
    t = arg.GetType().GetInterface(typeof(IList<>).Name).GetGenericArguments()[0];

    // if you expect multiple instances of IList<>, it gets more complicated;
    // we'll take just the first one we find
    t = arg.GetType().GetInterfaces().Where(
        i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>))
        .First().GetGenericArguments()[0];
}

如果您正在寻找 TIList<T>它变得复杂,因为您实际上可以声明一个类型,如 class FooBar: IList<Foo>, IList<Bar> .这就是为什么最后一个函数提供了几种不同的可能性。如果您希望在出现歧义的情况下抛出异常,请选择第一种可能性。如果您只想随意选择一个,请选择第二个。如果您关心获得的是哪一个,则必须进行更多编码才能以某种方式选择最能满足您需求的一个。

关于C# 获取类型() : Code how to get the type of T in List<T> without actual elements?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4039179/

相关文章:

c# - 2个线程增加一个静态整数

c# - Dapper 可以批处理一组存储过程调用吗?

java - BO <=> Java 中的 DTO 映射器

c# - 如何获取所有当前加载的程序集的列表?

typescript - 未初始化的 TypeScript 类属性不会被迭代

c# - 有没有一种类型化的方法来在 C# 中声明方法名称

c# - 在 GridView 中操作当前编辑的行

c# - 无法通过 AJAX 发送大文本

c# - 如何在 XML 文档中包含 DTD

java - 在 Scala 中使用 Java 类时出现 "ambiguous reference to overloaded definition"