Convert “C# friendly type” name to actual type: “int” => typeof(int)

前端 未结 5 2165
旧时难觅i
旧时难觅i 2021-02-07 23:46

I want to get a System.Type given a string that specifies a (primitive) type\'s C# friendly name, basically the way the C# compiler d

5条回答
  •  佛祖请我去吃肉
    2021-02-08 00:26

    Here's my stab at it. I approached it using two similar libraries:

    • Mono C# compiler-as-a-service
    • MS Roslyn C# compiler

    I think it's pretty clean and straightforward.

    Here I'm using Mono's C# compiler-as-a-service, namely the Mono.CSharp.Evaluator class. (It's available as a Nuget package named, unsurprisingly, 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 counterpart from "the friends in building 41" aka Roslyn...

    Later:

    Roslyn is almost as easy to install - once you figure out what's what. I ended up using Nuget package "Roslyn.Compilers.CSharp" (Or get it as a VS add-in). Just be warned that Roslyn requires a .NET 4.5 project.

    The code is even cleaner:

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

提交回复
热议问题