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
?
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
The first step to dynamically invoking a generic method with reflection is to use reflection to get access to the MethodInfo of the generic method. To do that simply do this: var methodInfo = typeof(ClassWithGenericMethod). GetMethod("MethodName");
A generic type is like a template. You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.
Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With