C# 如何从字符串实例化类型及其值?
我有类似的代码:C# 如何从字符串实例化类型及其值?,c#,.net,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)
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);
class Foo{
词典;
创建空(字符串myType、字符串myValue)
{
var instance=Type.Instanciate(myType)//我该怎么做?
if(变量IsPrimitive)
{
var.GetType().Parse(myValue)//我知道这是存在的……如何调用?
字典[instance.GetType()]=实例;
}
}
T GetValue(T myType){return(T)_dict[T];}
}
//用值填充
foo.Create(“System.Int32”、“15”);
Create(“System.String”,“My String”);
foo.Create(“System.Boolean”、“False”);
//访问值
bool b=获取值(b);
所以我的问题是:a) 如何实例化类型
b) 当支持解析时,从字符串解析类型值 a) 如何实例化该类型 你在找我 b) 当支持解析时,从字符串解析类型值 您正在寻找。
- 获取类型:
- 从类型对象实例化类型:(在代码中实际上不需要这个。)
- 从字符串转换:
mscorlib
或当前正在执行的程序集中,则需要包含程序集名称(如果它是强名称,则需要包含版本信息)
下面是一个使用原始代码的完整示例。请注意,GetValue
不需要普通参数,因为您已经给出了类型参数(t)
使用系统;
使用System.Collections.Generic;
公共类Foo{
字典_dict=新字典();
创建公共void(字符串myType、字符串myValue)
{
Type Type=Type.GetType(myType);
对象值=Convert.ChangeType(myValue,type);
_dict[type]=值;
}
public T GetValue(){return(T)_dict[typeof(T)];}
}
课堂测试
{
静态void Main()
{
Foo-Foo=新的Foo();
//用值填充
foo.Create(“System.Int32”、“15”);
Create(“System.String”,“My String”);
foo.Create(“System.Boolean”、“False”);
Console.WriteLine(foo.GetValue());
Console.WriteLine(foo.GetValue());
Console.WriteLine(foo.GetValue());
}
}
您可以尝试Activator.CreateInstance
它有接收类型的签名,但没有参数,或者有一个对象数组,而这些对象是参数。还有一件事:在字典中保留对新实例的引用可能会产生意想不到的后果:字典对对象的引用将阻止收集它。如果这就是你想要的,那也没关系,但首先要确保你已经看透了它的所有含义。奎斯顿昨天不是这样问的吗?我好像在做家庭作业。如果链接没有被删除,我会查看一下……女士们,先生们,这个男人从不睡觉!同时又精彩又简洁!说得好!在我的例子中,这并不重要,因为这些是从未收集过的配置元素。
using System.Reflection;
public void Create(string myType, string myValue)
{
Type type = Type.GetType(myType);
if (type.IsPrimitive)
{
MethodInfo Parse = type.GetMethod("Parse");
Parse.Invoke(null, new object[] { myValue });
...
}
}
using System.Reflection;
public void Create(string myType, string myValue)
{
Type type = Type.GetType(myType);
if (type.IsPrimitive)
{
MethodInfo Parse = type.GetMethod("Parse");
Parse.Invoke(null, new object[] { myValue });
...
}
}