简体   繁体   中英

Generics Type parameters and Types

I have some code that works like the below. I was wondering if its possible to get a Type object for the generic type passed to the DoSomething function. I realise that T is a type parameter but how would i turn this into a type object. The dosomething function is in a class where I want to know the underlying type used by the list object.

[STAThread]
static void Main(string[] args)
{
    List<string> stringList = new List<string>();
    DoSomething(stringList); 
}
public void DoSomething<T>(List<T> collection)
{
    //Type myType = T; ??!!? 
    //do something here with the list.
}

Just use:

Type type = typeof(T);

Generic parameters are like any other type except you don't know what exactly that type is at compile time, so it is assumed it is the uppermost in the object hierarchy which fits the type constraints given (for no constraints its System.Object).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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