将“C#friendly type”转换为实际类型:“int”=> typeof运算(INT)

时间:2013-06-07 12:20:50

标签: c# .net reflection types

我希望System.Type给出 string ,指定(原始)类型的 C#友好名称,基本上就是C#的方式编译器在读取C#源代码时会这样做。

我觉得描述我所追求的是以单元测试形式的最佳方式。

我希望存在一种通用技术可以使所有下面的断言通过,而不是试图对特殊C#名称的特殊情况进行硬编码。

Type GetFriendlyType(string typeName){ ...??... }

void Test(){
    // using fluent assertions

    GetFriendlyType( "bool" ).Should().Be( typeof(bool) );
    GetFriendlyType( "int" ).Should().Be( typeof(int) );

    // ok, technically not a primitive type... (rolls eyes)
    GetFriendlyType( "string" ).Should().Be( typeof(string) ); 

    // fine, I give up!
    // I want all C# type-aliases to work, not just for primitives
    GetFriendlyType( "void" ).Should().Be( typeof(void) );
    GetFriendlyType( "decimal" ).Should().Be( typeof(decimal) ); 

    //Bonus points: get type of fully-specified CLR types
    GetFriendlyName( "System.Activator" ).Should().Be(typeof(System.Activator));

    //Hi, Eric Lippert! 
    // Not Eric? https://stackoverflow.com/a/4369889/11545
    GetFriendlyName( "int[]" ).Should().Be( typeof(int[]) ); 
    GetFriendlyName( "int[,]" ).Should().Be( typeof(int[,]) ); 
    //beating a dead horse
    GetFriendlyName( "int[,][,][][,][][]" ).Should().Be( typeof(int[,][,][][,][][]) ); 
}

到目前为止我尝试了什么:

这个问题是an older question of mine的补充,询问如何从类型中获取“友好名称”。

该问题的答案是:使用CSharpCodeProvider

using (var provider = new CSharpCodeProvider())
{
    var typeRef = new CodeTypeReference(typeof(int));
    string friendlyName = provider.GetTypeOutput(typeRef);
}

我无法弄清楚如何(或者如果可能)以相反的方式执行它并从CodeTypeReference获取实际的C#类型(它还有一个需要string的ctor)

var typeRef = new CodeTypeReference(typeof(int));

5 个答案:

答案 0 :(得分:11)

如果已经解决了,你有没有大部分工作?

以下为http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx提供了所有内置C#类型,以及void

using Microsoft.CSharp;
using System;
using System.CodeDom;
using System.Reflection;

namespace CSTypeNames
{
    class Program
    {
        static void Main(string[] args)
        {
            // Resolve reference to mscorlib.
            // int is an arbitrarily chosen type in mscorlib
            var mscorlib = Assembly.GetAssembly(typeof(int));

            using (var provider = new CSharpCodeProvider())
            {
                foreach (var type in mscorlib.DefinedTypes)
                {
                    if (string.Equals(type.Namespace, "System"))
                    {
                        var typeRef = new CodeTypeReference(type);
                        var csTypeName = provider.GetTypeOutput(typeRef);

                        // Ignore qualified types.
                        if (csTypeName.IndexOf('.') == -1)
                        {
                            Console.WriteLine(csTypeName + " : " + type.FullName);
                        }
                    }
                }
            }

            Console.ReadLine();
        }
    }
}

这是基于几个假设,我认为在撰写本文时这些假设是正确的:

  • 所有内置C#类型都是mscorlib.dll的一部分。
  • 所有内置C#类型都是System命名空间中定义的类型的别名。
  • 通过CSharpCodeProvider.GetTypeOutput调用返回的只有内置C#类型的名称没有单个'。'在他们中。

输出:

object : System.Object
string : System.String
bool : System.Boolean
byte : System.Byte
char : System.Char
decimal : System.Decimal
double : System.Double
short : System.Int16
int : System.Int32
long : System.Int64
sbyte : System.SByte
float : System.Single
ushort : System.UInt16
uint : System.UInt32
ulong : System.UInt64
void : System.Void

现在我只需坐下来等待Eric来告诉我 我的错误。我接受了我的命运。

答案 1 :(得分:5)

'int','bool'等别名不是.NET Framework的一部分。在内部,它们被转换为System.Int32,System.Boolean等.Type.GetType(“int”)应该返回null。最好的方法是通过使用字典来映射别名与其类型,例如

        Dictionary<string, Type> PrimitiveTypes = new Dictionary<string, Type>();
        PrimitiveTypes.Add("int", typeof(int));
        PrimitiveTypes.Add("long", typeof(long));
        etc.etc..

答案 2 :(得分:5)

以下是使用Roslyn

执行此操作的方法
using System;
using System.Linq;
using Roslyn.Scripting.CSharp;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetType("int[,][,][][,][][]"));
            Console.WriteLine(GetType("Activator"));
            Console.WriteLine(GetType("List<int[,][,][][,][][]>"));
        }

        private static Type GetType(string type)
        {
            var engine = new ScriptEngine();
            new[] { "System" }
                .ToList().ForEach(r => engine.AddReference(r));
            new[] { "System", "System.Collections.Generic" }
                .ToList().ForEach(ns => engine.ImportNamespace(ns));
            return engine
                .CreateSession()
                .Execute<Type>("typeof(" + type + ")");
        }
    }
}

答案 3 :(得分:3)

这是一种方法:

public Type GetType(string friendlyName)
{
    var provider = new CSharpCodeProvider();

    var pars = new CompilerParameters
    {
        GenerateExecutable = false,
        GenerateInMemory = true
    };

    string code = "public class TypeFullNameGetter"
                + "{"
                + "     public override string ToString()"
                + "     {"
                + "         return typeof(" + friendlyName + ").FullName;"
                + "     }"
                + "}";

    var comp = provider.CompileAssemblyFromSource(pars, new[] { code });

    if (comp.Errors.Count > 0)
        return null;

    object fullNameGetter = comp.CompiledAssembly.CreateInstance("TypeFullNameGetter");
    string fullName = fullNameGetter.ToString();            
    return Type.GetType(fullName);
}

然后,如果你传入“int”,“int []”等,你会得到相应的类型。

答案 4 :(得分:0)

这是我对它的刺痛。我使用两个类似的库来接近它:

  • Mono C#compiler-as-a-service
  • MS Roslyn C#编译器

我认为它非常简洁明了。

这里我使用的是Mono的C#编译器即服务,即Mono.CSharp.Evaluator类。 (它以Nuget package命名,不出所料,Mono.CSharp

using Mono.CSharp;

    public static Type GetFriendlyType(string typeName)
    {
        //this class could use a default ctor with default sensible settings...
        var eval = new Mono.CSharp.Evaluator(new CompilerContext(
                                                 new CompilerSettings(),
                                                 new ConsoleReportPrinter()));

        //MAGIC! 
        object type = eval.Evaluate(string.Format("typeof({0});", typeName));

        return (Type)type;
    }

Up next:来自“the friends in building 41”又名Roslyn的对手......

后来:

Roslyn几乎一样容易安装 - 一旦你弄明白什么是什么。我最终使用Nuget package "Roslyn.Compilers.CSharp"(或者将其作为VS add-in)。请注意,Roslyn 需要一个.NET 4.5项目。

代码更清晰:

using Roslyn.Scripting.CSharp;

    public static Type GetFriendlyType(string typeName)
    {
        ScriptEngine engine = new ScriptEngine();
        var type = engine.CreateSession()
                         .Execute<Type>(string.Format("typeof({0})", typeName));
        return type;
    }