Get a C # type type link from a CLR type name

Given an object of type .NET found by reflection, is it possible to print or decompile this type nicely as a C # declaration, taking into account aliases of C # types, etc.

For instance,

Int32 -> int String -> string Nullable<Int32> -> int? List<au.net.ExampleObject> -> List<ExampleObject> 

I want to be able to print methods close to what was originally written in the source.

If there is nothing in the .NET Framework, is there a third-party library? Perhaps I could take a look at ILSpy .

+6
source share
5 answers

See this answer.

Example:

 using System.CodeDom; using System.CodeDom.Compiler; CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); var typeRef = new CodeTypeReference("System.Nullable`1[System.Int32]"); string typeOutput = provider.GetTypeOutput(typeRef); // "System.Nullable<int>" 

This will help you with int and string things, as well as with generics, however you will have to work out Nullable<T> -> T? and using .

+7
source

Aliases are compiled for what they are an alias for. You will never know whether it was in string or string in the source, and frankly, I don’t understand why it matters.

+1
source

There are only 15 aliases (+ Nullable) . Just use string.Replace on them.

+1
source

There is a solution for type declarations in another post . You can extend it to easily support type aliases.

0
source

This article has a C # source for a method that will do this: http://www.codeproject.com/Tips/621812/User-friendly-names-for-Types

0
source

Source: https://habr.com/ru/post/889932/


All Articles