我想得到一个System.Type
给定一个string
指定(原始)类型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[,][,][][,][][]) );
}
到目前为止我尝试过的:
这个问题是对我的一个较旧的问题 https://stackoverflow.com/q/4615553/11545询问如何从类型中获取“友好名称”。
这个问题的答案是:使用CSharpCodeProvider
using (var provider = new CSharpCodeProvider())
{
var typeRef = new CodeTypeReference(typeof(int));
string friendlyName = provider.GetTypeOutput(typeRef);
}
我无法弄清楚如何(或者如果可能的话)以相反的方式进行操作并从CodeTypeReference
(它还有一个演员需要string
)
var typeRef = new CodeTypeReference(typeof(int));