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)
:
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)
.
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.
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>();
. You wanna add the where T : new()
constraint to your method though, to make this easy. 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.
You can get the type of T using typeof..
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
}
精彩评论