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

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

    Don't you have most of if worked out already?

    The following gives you all built-in C# types as per http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx, plus 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();
            }
        }
    }
    

    This is based on several assumptions which I believe to be correct as at the time of writing:

    • All built-in C# types are part of mscorlib.dll.
    • All built-in C# types are aliases of types defined in the System namespace.
    • Only built-in C# types' names returned by the call to CSharpCodeProvider.GetTypeOutput do not have a single '.' in them.

    Output:

    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
    

    Now I just have to sit and wait for Eric to come and tell me just how wrong I am. I have accepted my fate.

提交回复
热议问题