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

前端 未结 5 2164
旧时难觅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:13

    Here's a way to do it by using 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"));
            }
    
            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("typeof(" + type + ")");
            }
        }
    }
    

提交回复
热议问题