Last active
June 5, 2017 17:19
-
-
Save jmarolf/57352bac8d3f20cf47249e00fb48a8ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Microsoft.CodeAnalysis; | |
using Microsoft.CodeAnalysis.CSharp; | |
namespace GetTypeName | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var str = GetFullName(typeof(List<int>)); | |
Console.WriteLine(str); | |
} | |
private static string GetFullName(Type type) | |
{ | |
var reference = MetadataReference.CreateFromFile(type.Assembly.Location); | |
var mscorlb = MetadataReference.CreateFromFile(typeof(Object).Assembly.Location); | |
var compilation = CSharpCompilation.Create("test", references: new[] { reference, mscorlb }); | |
if (type.IsConstructedGenericType) | |
{ | |
var def = type.GetGenericTypeDefinition(); | |
var args = type.GetGenericArguments(); | |
var namedType = compilation.GetTypeByMetadataName(def.FullName); | |
var typeArguments = args.Select(a | |
=> compilation.GetTypeByMetadataName(a.FullName)).ToArray(); | |
var constructedNamedType = namedType.Construct(typeArguments); | |
return constructedNamedType.ToDisplayString(); | |
} | |
else | |
{ | |
var namedType = compilation.GetTypeByMetadataName(type.FullName); | |
return namedType.ToDisplayString(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment