繁体   English   中英

如何将 Class 构造函数或类型作为参数传递

[英]How to pass a Class constructor or Type as a parameter

我希望从它的类型或构造函数中动态构造一个 object。

var typeList = new List<Type>();
typeList.Add(String); // Error: 'string' is a type, which is not valid in this context
typeList.Add(CustomObject); // Error: 'CustomObject' is a type, which is not valid in this context

因为我想做一些事情

// Pseudo code
foreach(var t in typeList){
  var obj = new t();
}

如果您只需要列表来初始化 object 您可以将列表从List<Type>更改为List<Func<object>>并像这样使用它

var initList = new List<Func<object>>();
initList.Add(() => string.Empty);
initList.Add(() => new CustomClass());

foreach (var init in initList)
    Console.WriteLine(init());

实际操作https://dotnetfiddle.net/ubvk20

尽管我必须说,我相信对于您要解决的问题会有更好、更理想的解决方案。

如果您有一个List<Type> ,那么您必须使用typeof来获取给定 class 的实际Type实例。

var typeList = new List<Type>();

typeList.Add(typeof(string));
typeList.Add(typeof(CustomClass));

为了创建存储在typeList中的Type的实例,您可以使用Activator class 具体来说, Activator.CreateInstance

foreach (var type in typeList)
{
   var inst = Activator.CreateInstance(type);
}

但是,这仍然存在一些您必须解决的问题。 例如,上面代码中的inst将是对object的引用。 如果要将其用作该类型的实例,则必须想办法将其转换为任何type

此外,上面的代码仅适用于具有不带参数的构造函数的类型。 如果typeList中的类型没有无参数构造函数,则上面的代码将抛出MissingMethodException 这尤其值得一提,因为在您的示例中,您将string添加到typeList ,但string没有空的 constructor

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM