将要创建的带有参数的对象列表传递给构造函数或方法
本文关键字:构造函数 列表 方法 对象 创建 参数 | 更新日期: 2023-09-27 18:35:04
基本上我要做的是创建一个可以使用以下命令批量创建对象的类
Activator.CreateInstance(Type type, params object[] args)
我需要将所有对象蓝图传递给名为 ObjectMap 的类的构造函数。它需要是类型和参数的对。它也可以是另一个类中的方法,而不是构造函数(如果允许解决方案(。
有点像
new ObjectMap([Type, somevalue, somevalue, somevalue], [Type, somevalue], [Type] ...)
或
Resources.AddObjectMap([Type, somevalue, somevalue, somevalue], [Type, somevalue], [Type] ...)
我不知道如何做到这一点,以便您可以使用可变数量的参数(甚至 0(传递可变数量的对。哎呀,我什至很难解释这个问题。问我任何你不清楚的事情=S
维勒
我建议你将"类型和参数"封装到一个特定的类型中......然后,您可以使用该数组的params
数组。例如:
// TODO: Find a better name :)
public class TypeBlueprint
{
public Type Type { get; set; }
public List<object> Arguments { get; set; }
public TypeBlueprint()
{
this.Arguments = new List<object>();
}
public TypeBlueprint(Type type, params object[] arguments)
{
this.Type = type;
this.Arguments = arguments.ToList();
}
}
然后:
public ObjectMap(params TypeBlueprint[] blueprints)
并用以下命令调用它:
var map = new ObjectMap(new TypeBlueprint(typeof(Foo), "x", "y", "z"),
new TypeBlueprint { Type = typeof(Bar),
Arguments = { 1, 2, 3 } });
这演示了如何使用构造函数参数和对象初始值设定项来指定类型和参数。使用最适合您的方法。
我认为这就是你要的...(我认为我们的问题的真正答案是在函数参数列表中使用 params
(
实现:
public class ObjectMap
{
public object[] ActivatedObjects { get; private set; }
public ObjectMap(params object[][] itemsToMap)
{
ActivatedObjects = itemsToMap.Select(ActivateItem).ToArray();
}
private object ActivateItem(object[] itemToActivate)
{
return Activator.CreateInstance((Type)itemToActivate[0], itemToActivate.Skip(1).ToArray());
}
}
基本单元测试:
[TestClass]
public class UnitTest3
{
[TestMethod]
public void TestMethod1()
{
var map = new ObjectMap(new object[] {typeof(Class1)},
new object[] {typeof(Class2), "Arg One", 2});
Assert.AreEqual(2, map.ActivatedObjects.Length);
Assert.IsInstanceOfType(map.ActivatedObjects[0], typeof(Class1));
Assert.IsInstanceOfType(map.ActivatedObjects[1], typeof(Class2));
}
}
public class Class1
{
public Class1()
{
}
}
public class Class2
{
public Class2(string arg1, int arg2)
{
}
}