我有类似的代码:
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 时,从字符串中解析类型值。
最佳答案
- 获取类型:
Type.GetType()
- 从类型对象实例化类型:
Activator.CreateInstance
(您的代码中实际上不需要这个。) - 从字符串转换:
Convert.ChangeType
请注意,如果类型不在 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/