简体   繁体   中英

How can I get the name of a generic class programmatically?

I want to get the name of a class dynamically. I can use this:

public void RequestData<TResult>()
{
     var myName = typeof(TResult).Name;
}

Which works fine eg if TResult is of type MyClass then myName would equal "MyClass"

But if TResult is of type

List<MyClass> 

I still want myName to equal "MyClass" ... at the moment it will be "List`1"

So if TResult is going to be of type List how can I programmatically know that it's a List and then pick out the name of the type of this list?

That can be done with the help of a few methods on the Type .

public void RequestData<TResult>()
{
    Type type = typeof(TResult);
    string myName;
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
    {
        myName = type.GetGenericArguments()[0].Name;
    }
    else
    {
        myName = typeof(TResult).Name;
    }
}

You can get the 'leftmost' inner generic type with

public static Type GetInnermost(Type t)
{
    while(t.IsGenericType)
    {
        t = t.GetGenericArguments()[0];
    }
    return t;
}

then you can do:

var myName = GetInnermost(typeof(TResult)).Name;

then eg

RequestData<List<IEnumerable<Task<IObserverable<string>>>();

will have a name of String .

You could use the GetGenericArguments method, which returns an array of Type objects that represent the type arguments of a generic type or the type parameters of a generic type definition. (MSDN).

For sample:

public void RequestData<TResult>()
{
     var myName = typeof(TResult).Name;
     var type = typeof(TResult)
     if (type.IsGenericType)
     {
         myName = type.GetGenericArguments().First().Name;
     }
}

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