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

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

    Here's one way to do it:

    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);
    }
    

    Then if you pass in "int", "int[]" etc you get the corresponding type back.

提交回复
热议问题