如何基于键值对创建对象

时间:2012-07-30 07:18:46

标签: c# .net design-patterns

假设您拥有键/值对的集合。例如: -

dictionary<string,string> myObjectToBeCreated = new dictionary<string,string>();
myObjectToBeCreated.Add("int","myIntObject");
myObjectToBeCreated.Add("string","myStringObject");
myObjectToBeCreated.Add("employee","myEmployeeObject");

现在,如何使用myObjectToBeCreated创建名为myIntObject的int对象。这样的事情: -

int myIntObject;
string myStringObject;
Employee myEmployeeObject = new Employee();

注意:您只拥有该集合。此集合具有dataTypes和objectnames。如何使用特定名称(在字典中定义)创建那些dataType的对象。您可以传递此集合(MyObjectsToBeCreated以您想要的任何方法)。但最后你应该得到类型的对象(在字典中指定)。

您可以使用任何设计模式,例如 factory / dependency / builder 。或者你甚至可以自由地使用模式实现上述目标。

3 个答案:

答案 0 :(得分:3)

仅使用自定义类的类名是不够的。你需要整个命名空间。

然后假设您的类型有无参数构造函数,您可以使用

Activator.CreateInstance(Type.GetType(strNamespace + strType))

Activator.CreateInstance(strNamespace, strType)

答案 1 :(得分:2)

如果您可以使用Type而不是string:

Dictionary<Type, object> yourObjects = new Dictionary<Type, object>();
yourObjects[typeof(int)] = 5;
yourObjects[typeof(string)] = "bamboocha";


var integer = (int)yourObjects[typeof(int)];

答案 2 :(得分:1)

var myObjects = new Dictionary<string, Object>();

foreach (var pair in myObjectToBeCreated)
{
    var strNamespace = //set namespace of 'pair.Key'
    myObjects.Add(pair.Value, Activator.CreateInstance(strNamespace, pair.Key));
}

// and using it
var myEmployeeObject = (Employee)myObjects["myEmployeeObject"];
相关问题