简体   繁体   English

如何获取泛型T作为函数C#中声明的对象

[英]How to get the generic type T as object declared in a function C#

    public static List<T> GetColumnValuesByHeader<T>(string docName)
    {
      //  How can i get T as Customer or Employee in here?    
    }

List<Customer> customers = GetColumnValuesByHeader<Customer>("Customers.dat")
List<Employee> employees= GetColumnValuesByHeader<Employee>("Employees.dat")

Use typeof(T) : 使用typeof(T)

public static List<T> GetColumnValuesByHeader<T>(string docName)
{
    // Will print Customer or Employee appropriately
    Console.WriteLine(typeof(T));
}

Now what exactly you do with that afterwards is up to you... 现在,您究竟该怎么做才由您决定...

If you actually need to handle the cases differently, then I'd be tempted to write separate methods to start with. 如果您实际上需要以不同的方式处理案例,那么我很想编写单独的方法作为开始。 Generics are really designed for algorithms which behave the same way for any type. 泛型实际上是为算法设计的,该算法对于任何类型的行为都相同。 There are exceptions to every rule, of course - such as optimizations in Enumerable.Count<T> ... and if you're fetching properties by reflection, for example, then that's a reasonable use of typeof(T) . 当然,每条规则都有例外-例如Enumerable.Count<T>优化……,例如,如果您通过反射来获取属性,则这是对typeof(T)的合理使用。

As Jon Skeet said you can use typeof to get the type of T. You can also use the Activator class to create an instance of that class. 正如Jon Skeet所说,您可以使用typeof来获取T的类型。您还可以使用Activator类来创建该类的实例。

Type theType = typeof(T);
object obj = Activator.CreateInstance(theType);

Assuming you want to create many T to populate your list, the simplest way is to use Activator.CreateInstance<T>(); 假设您要创建许多T来填充列表,最简单的方法是使用Activator.CreateInstance<T>(); . You wanna add the where T : new() constraint to your method though, to make this easy. 您想将where T : new()约束添加到您的方法中,以简化此过程。 It'll assume Customer and Employee each have a default constructor - if that isn't the case, you can still use CreateInstance() , but you'll need to grab the correct arguments to pass by getting the ConstructorInfo for each type. 假设Customer和Employee都有默认的构造函数-否则,您仍然可以使用CreateInstance() ,但是您需要获取正确的参数以获取每种类型的ConstructorInfo来传递。

You can get the type of T using typeof.. 您可以使用typeof获得T的类型。

Type t = typeof(T);
if (t == typeof(Employee))
{
    //Do something here ...
}
if (type of T Is Customer) {
 //Perform action for customer
} else

if (type of T Is Employee) {
 //Perform action for Employee
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM