c# - 如何从字符串实例化类型及其值?

标签 c# .net

我有类似的代码:

class Foo {     
  Dictionary<Type, Object> _dict;

  void Create(string myType, string myValue)
  {
    var instance = Type.Instanciate(myType)  // How do I do this?
    if (var.IsPrimitive)
    {
      var.GetType().Parse(myValue)   // I know this is there...how to invoke?
      Dictionary[instance.GetType()] = instance;
    }
  }

  T GetValue<T>(T myType) { return (T)_dict[T]; }
}

// Populate with values
foo.Create("System.Int32", "15");
foo.Create("System.String", "My String");
foo.Create("System.Boolean", "False");

// Access a value
bool b = GetValue(b);

所以我的问题是:
a) 如何实例化类型
b) 当支持 Parse 时,从字符串中解析类型值。

最佳答案

请注意,如果类型不在 mscorlib 或当前正在执行的程序集中,您将需要包括程序集名称(如果它是强命名的,还需要包括版本信息)。

这是一个使用您的原始代码的完整示例。请注意,GetValue 不需要普通参数,因为您已经提供了类型参数 (T)。

using System;
using System.Collections.Generic;

public class Foo {     
  Dictionary<Type, Object> _dict = new Dictionary<Type, Object>();

  public void Create(string myType, string myValue)
  {
      Type type = Type.GetType(myType);
      object value = Convert.ChangeType(myValue, type);
      _dict[type] = value;
  }

  public T GetValue<T>() { return (T)_dict[typeof(T)]; }
}


class Test
{
    static void Main()
    {
        Foo foo = new Foo();

        // Populate with values
        foo.Create("System.Int32", "15");
        foo.Create("System.String", "My String");
        foo.Create("System.Boolean", "False");

        Console.WriteLine(foo.GetValue<int>());
        Console.WriteLine(foo.GetValue<string>());
        Console.WriteLine(foo.GetValue<bool>());
    }
}

关于c# - 如何从字符串实例化类型及其值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/645826/

相关文章:

c# - Convert.ChangeType 快捷方式吗?

c# - 'Anonymously Hosted DynamicMethods Assembly' 到底是什么,我怎样才能让它手动加载?

c# - 一个 xelement 和多个命名空间

javascript - 如何在ASP.NET中的Linkbutton中管理右键单击 "Open in new tab"和 "Open in new windows"?

c#更改相对或绝对uri的文件名

c# - 正则表达式查找信用卡模式不排除超过 16 位的信用卡模式

c# - 在 FluentMigrator 上创建表之前检查表是否存在

c# - 需要在线创建圆角吗?

c# - 定期看到 ASP.NET 错误 CS0656 : Missing compiler required member

c# - 从模块导入特定 cmdlet 以在 Runspacepool 中使用