Reputation: 440
i've made a mini project to get with reflection all the interfaces from the dll i've imported, that inherits from my "IBase" interface like this
Type[] services = typeof(DataAccess.IXXX).Assembly.GetTypes();
foreach (Type SC in services)
{
if (SC.IsInterface)
{
if (SC.GetInterfaces().Contains(typeof(DataAccess.IBase)))
{
file.WriteLine(SC.Name);
}
}
}
The problem is that a lot of my interfaces contains generics
public interface IExample<TKey, Tvalue, TCount> : IBase
But my SC.Name write that like this
IExample'3
Can you help me ?
Upvotes: 2
Views: 128
Reputation: 4069
As you can see, the .NET name property doesn't show you the generic parameter types as part of the name. You have to get the parameter types from GetGenericArguments.
Here is a method returns the name of a generic type in the C# style. It is recursive, so it can handle generics that have generic types as parameters i.e IEnumerable<IDictionary<string, int>>
using System.Collections.Generic;
using System.Linq;
static string FancyTypeName(Type type)
{
var typeName = type.Name.Split('`')[0];
if (type.IsGenericType)
{
typeName += string.Format("<{0}>", string.Join(",", type.GetGenericArguments().Select(v => FancyTypeName(v)).ToArray()));
}
return typeName;
}
Upvotes: 1
Reputation: 9648
IExample'3
is the internal name of the of an interface with 3 generic type arguments (as you have probably already guessed). To get the generic type arguments of a class or interface use the Type.GetGenericArguments
You can use something like this to print the correct name
var type = typeof(IExample<int, double>);
var arguments = Type.GetGenericArguments(type);
if(arguments.Any())
{
var name = argument.Name.Replace("'" + arguments.Length, "");
Console.Write(name + "<");
Console.Write(string.Join(", ", arguments.Select(x => x.Name));
Console.WriteLine(">")
}
else
{
Console.WriteLine(type.Name);
}
Upvotes: 4