我如何实例化一个类型,它的值从字符串? [英] How do I instantiate a type and its value from a string?

查看:203
本文介绍了我如何实例化一个类型,它的值从字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有code与此类似:

I have code similar to this:

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);

所以我的问题是:
   一)如何实例的类型
   从字符串B)解析类型值支持解析的时候。

So my questions are:
a) How do I instantiate the type
b) Parse the type value from a string when Parse is supported.

推荐答案

请注意,如果类型不在的mscorlib 或当前执行的程序集,你需要包括程序集名称(和版本信息,如果它的强命名)

Note that if the type isn't in mscorlib or the currently executing assembly, you'll need to include the assembly name (and version information if it's strongly named).

下面是一个使用你原来的code一个完整的例子。需要注意的是的GetValue 并不需要一个正常的参数,因为你已经给类型参数(T)。

Here's a complete example using your original code. Note that GetValue doesn't need a normal parameter, as you've already given the type parameter (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>());
    }
}

这篇关于我如何实例化一个类型,它的值从字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆