转换“c#友好类型”名称改为实际类型:"int"=比;typeof (int)

本文关键字:quot int 类型 typeof 转换 | 更新日期: 2023-09-27 18:17:19

我想得到一个给定 string System.Type,它指定了一个(原始)类型的 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[,][,][][,][][]) ); 
}

我试过了:

这个问题是我以前问的一个问题的补充:如何从一个类型中获得"友好的名称"。

这个问题的答案是:使用CSharpCodeProvider

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

我无法弄清楚如何(或如果可能的话)以另一种方式做到这一点,并从CodeTypeReference获得实际的c#类型(它也有一个需要string的角色)

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

转换“c#友好类型”名称改为实际类型:"int"=比;typeof (int)

你不是已经算出大部分了吗?

下面给出了所有内置的c#类型,如http://msdn.microsoft.com/en-us/library/ya5y69ds.aspx,加上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命名空间中定义的类型的别名。
  • 只有内置c#类型的名称由调用CSharpCodeProvider.GetTypeOutput返回没有单一的'。
输出:

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过来告诉我我错了。我已经接受了我的命运。

别名如'int','bool'等不是。net框架的一部分。在内部,它们被转换成System。Int32,系统。布尔等等。Type.GetType("int")应该返回null。最好的方法是使用字典将别名与其类型进行映射,例如

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

可以使用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 + ")");
        }
    }
}

有一种方法:

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[]"等,你会得到相应的类型返回

下面是我的尝试。我使用了两个类似的库:

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

我认为这是相当干净和直接的。

这里我使用Mono的c#编译器即服务,即Mono.CSharp.Evaluator类。(它可以作为Nuget包获得,不出所料,名为monoc sharp)
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;
    }

下一个:来自"41号楼的朋友们"的对手,也就是Roslyn…

后:

Roslyn几乎同样容易安装-一旦你弄清楚什么是什么。我最终使用Nuget包"Roslyn.Compilers"。(或者将其作为VS插件)。需要注意的是,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;
    }