通过将所需类型作为参数传递,从字符串值转换为特定类型

Vin*_*ngh 3 generics types type-conversion c#-4.0

我使用以下方法将字符串类型转换为泛型类型

public static T Parse<T>(string value)
{
    // or ConvertFromInvariantString if you are doing serialization
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
Run Code Online (Sandbox Code Playgroud)

我必须这样称呼它

Parse<Int32>(Some string value);
Parse<DateTime>(Some string value);
Run Code Online (Sandbox Code Playgroud)

我想that instead of giving the result type explicitly,我可以给它一样

Parse<Type.GetType("Int32")>(Some string value);
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 5

仿制药在这里不在考虑范围内.主要问题是您尝试使用类型标识的快捷方式.一个类型的名称是不是只是你在程序中使用的类型名称.它还包括声明它的名称空间,存储它的程序集的显示名称,程序集的版本号以及程序集强名称的公钥标记.换句话说,Type.AssemblyQualifiedName.

这要求您编写类似于此的代码:

 Parse(Type.GetType("System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089""), SomeStringValue);
Run Code Online (Sandbox Code Playgroud)

这将工作得很好.但我猜你不会喜欢写这个.否则,可以让您深入了解编译器在程序中读取"Int32"时所执行的操作.它将在其符号表中查找已添加的引用程序集,并注意该表中可能存在的匹配项,考虑使用指令有效.

你必须在你的程序中实现类似的东西.编译器的符号表的等价物是a Dictionary<string, Type>.您可以通过使用您希望使用短字符串名称的类型填充它来填充它.喜欢

  LookupTable.Add("Int32", typeof(int));
  LookupTable.Add("String", typeof(string));
  // etc...
Run Code Online (Sandbox Code Playgroud)

现在你可以写:

  Parse(LookupTable["Int32"], SomeStringValue);
Run Code Online (Sandbox Code Playgroud)

这将工作得很好.但我猜你不会喜欢写这个.很难击败编译器.