【问题标题】:Is there a way to convert "int" to typeof(int) in c#?有没有办法在 c# 中将“int”转换为 typeof(int)?
【发布时间】:2021-05-26 18:56:51
【问题描述】:

我知道我可以像这样从字符串名称中获取类型

Type intType = Type.GetType("System.Int32");

但是,如果我有这样的字符串怎么办

string[] typeNameArr = new string[] {"Int", "String", "DateTime", "Bool"};

如何将这些转换为实际类型?也许我可以从别名中获取完整的限定名,然后执行GetType

【问题讨论】:

  • 你的字符串数组是奇数。 Int 需要变为 intSystem.Int32,而 DateTime 需要变为 System.DateTime(没有 DateTime 语言别名)。我认为您将不得不对其中的一些进行特殊处理——查找知道Int 等的内容,然后尝试将System. 附加到那些不在您查找中的内容
  • 听起来您基本上想要一个Dictionary<string, Type> - 将您从网络服务中知道的每种类型添加到该字典中。
  • 此外,基于反序列化数据实例化任意类型是一个巨大的安全漏洞。 BCL 中隐藏了一些类型,当它们被实例化时,它们会做任意事情,攻击者可以使用它来执行远程代码执行。您必须将任何类型的对象创建列入已知安全类型的白名单
  • 没有。别名是 C# 语言的概念,但Type.GetType 由运行时提供,用于所有 CLR 语言
  • 你的字体真的有那么多变化吗?只写字典比摆弄反射要快。

标签: c#


【解决方案1】:

如果您使用完全限定名称,例如 "System.Int32" 最后您将能够通过 linq 访问它:

var types = typeNameArr.Select(c => Type.GetType(c));

另外:如果您的网络服务提供自定义名称,您需要映射或约定。例如:

var types = typeNameArr.Select(c => Type.GetType("System." + c));

var types = typeNameArr.Select(c => 
{
   switch (c)
   {
      "Int":
          return typeof(int);
      "Foo":
          return typeof(BarClass);  
      default:
          return  null
   }        
});

【讨论】:

  • 我从 WebService 获取这个数组,所以我不能在这里使用完全限定的名称。我需要一种将这些正确转换为实际 c# 类型的动态方法。
  • @Talha:但Int 既不是.NET 类型(即System.Int32)也不是C# 别名(即int 和小写i)!因此,恐怕您必须自己对转换表进行硬编码(例如,使用大型 switch 语句)。
  • @Heinzi 我知道。但是我可以改成小写。
  • @Talha:由于list of C# aliases 相当短且不太可能改变,我肯定会主张使用大型硬编码switch 语句,而不是使用一些框架魔法。
  • 此时你不妨做一个从stringType的映射:c switch { "Int" => typeof(int), ... }
【解决方案2】:

要获取所有原始类型及其别名,您可以编写:

string assemblyFullName = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
var assembly = Assembly.Load(assemblyFullName);
var primitiveTypes =
    assembly.DefinedTypes.Where(definedType => definedType.IsPrimitive && definedType != typeof(IntPtr) && definedType != typeof(UIntPtr));

using (var provider = new CSharpCodeProvider())
{
    var result = primitiveTypes.Select(x => (Alias: provider.GetTypeOutput(new CodeTypeReference(x)), Type: x));
}

会导致:

bool    typeof(Boolean)
byte    typeof(Byte)
char    typeof(Char)
double  typeof(Double)
short   typeof(Int16)
int     typeof(Int32)
long    typeof(Int64)
sbyte   typeof(SByte)
float   typeof(Single)
ushort  typeof(UInt16)
uint    typeof(UInt32)
ulong   typeof(UInt64)

【讨论】:

  • DateTime 怎么办?为什么要回答而不仅仅是参考thisthis 的评论?
  • 只需为其添加手动映射即可。为所有类型添加手动映射可能是最好的解决方案,只是想表明它也可以使用代码来完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 2011-12-21
  • 2020-05-02
  • 1970-01-01
  • 2016-07-22
  • 2012-02-04
相关资源
最近更新 更多