确保List <T>类型中的所有元素都是T.

gdo*_*ica 1 .net c# oop generics .net-2.0

我想验证所有List<T>的元素类型是什么T.

我可以有一个List<object>包含对象,字符串,整数,产品,供应商等,但在我的情况下,如果List<T>定义为List<object>所有元素必须是对象.

也就是说,我想确保元素的类型是传入泛型类型的确切类型,而不是继承链中的任何其他类型.

例:

public void Foo<T>(List<T> list)
{
    // if not all elements are of type T (not SubClass of T) throw exception

    //...    
}
Run Code Online (Sandbox Code Playgroud)

什么是最好的方法?

Geo*_*ett 8

假设if T是基类,则要禁止派生类.

if(list.Any(element => element.GetType() != typeof(T))
    throw new ArgumentException();
Run Code Online (Sandbox Code Playgroud)