Pregunta

I am trying to get the type name of T using this:

typeof(T).Name

The name of the class is ConfigSettings

Instead of returning ConfigSettings it is returning ConfigSettings`1.

Is there any specific reason why? How can I return the actual name without `1?

¿Fue útil?

Solución 2

The back-tick is indicative that the class is a generic type. Probably the easiest thing is to just lop off anything from the back-tick forward:

string typeName = typeof(T).Name;
if (typeName.Contains('`')) typeName = typeName.Substring(0, typeName.IndexOf("`"));

Otros consejos

Here is an extension method that will get the "real" name of a generic type along with the names of the generic type parameters. It will properly handle nested generic types.

public static class MyExtensionMethods
{
    public static string GetRealTypeName(this Type t)
    {
        if (!t.IsGenericType)
            return t.Name;

        StringBuilder sb = new StringBuilder();
        sb.Append(t.Name.Substring(0, t.Name.IndexOf('`')));
        sb.Append('<');
        bool appendComma = false;
        foreach (Type arg in t.GetGenericArguments())
        {
            if (appendComma) sb.Append(',');
            sb.Append(GetRealTypeName(arg));
            appendComma = true;
        }
        sb.Append('>');
        return sb.ToString();
    }
}

Here is a sample program showing its usage:

static void Main(string[] args)
{
    Console.WriteLine(typeof(int).GetRealTypeName());
    Console.WriteLine(typeof(List<string>).GetRealTypeName());
    Console.WriteLine(typeof(long?).GetRealTypeName());
    Console.WriteLine(typeof(Dictionary<int, List<string>>).GetRealTypeName());
    Console.WriteLine(typeof(Func<List<Dictionary<string, object>>, bool>).GetRealTypeName());
}

And here is the output of the above program:

Int32
List<String>
Nullable<Int64>
Dictionary<Int32,List<String>>
Func<List<Dictionary<String,Object>>,Boolean>

Is there any specific reason why?

It means that the type has one generic type argument.

How can I return the actual name without "`1"?

You can just find the index of ` (if it exists) and return the substring of the type name up to that character.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top