是否有可能创建一个基于字符串值,表示其类型的对象实例? [英] Is it possible to create an object instance based on a string value denoting its type?
问题描述
我试图动态地创建某种类型的基础上我的XML文档中的字符串中的LINQ到XML查询的对象。我已经习惯了能够动态地创建任何类型的PHP和JavaScript的对象,只需能写的东西,如:
I'm trying to dynamically create an object of a certain type in a LINQ-to-XML query based on a string within my XML document. I'm used to being able to dynamically create an object of any type in PHP and JavaScript by simply being able to write something like:
$obj = new $typeName();
在理想情况下,我希望能够做这样的事情:
Ideally, I'd like to be able to do something like:
List<someObj> = (from someObjs in XMLfile
select new someObj()
{
Name = (string)someObjs.Element("name"),
NestedObj = new someObjs.Element("nestedObj").Element("type")()
{
NestedName = (string)someObjs.Element("nestedObj").Element("name")
}
}).ToList();
我只是不知道如何做没有抓住当前执行的程序集的保持。
I just can't figure out how to do it without grabbing a hold of the current executing assembly.
推荐答案
您可以使用:
Activator.CreateInstance(Type.GetType(typeName))
当然,这只是作品类型的参数的构造函数。
Of course, this only works for types with a parameterless constructor.
更新(初始化对象):
您可以使用C#4动态类型的功能来设置新创建的对象的属性:
You can use C# 4 dynamic typing features to set properties of the newly created object:
dynamic newObj = Activator.CreateInstance(Type.GetType(typeName));
newObj.NestedName = str;
在一个LINQ到XML查询的背景下,你可能不得不求助于有明确的身体lambda语法
In the context of a LINQ to XML query, you may have to resort to lambda syntax with explicit body:
var list = XMLFile.Select(someObjs => {
dynamic nestedObj = Activator.CreateInstance(
Type.GetType(someObjs.Element("nestedObj").Element("type")));
nestedObj.NestedName = (string)someObjs.Element("nestedObj").Element("name");
return new someObj {
Name = (string)someObjs.Element("name"),
NestedObj = nestedObj
};
}).ToList();
这篇关于是否有可能创建一个基于字符串值,表示其类型的对象实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!