传递一个类型参数并声明一个列表

use*_*153 1 c# reflection

public static List<customModel> getList(type customModel)
{ 
  List<customModel> tempList = new List<customModel>(10);
  return tempList;
}
Run Code Online (Sandbox Code Playgroud)

是否可以返回从其他地方传递的类型列表?我一直在做我自己的项目,并注意到如果有任何方法可以做到这一点,我的代码将更加简单.

mus*_*fan 10

你的意思是使用这样的泛型:

public static List<T> getList<T>()
{ 
  List<T> tempList = new List<T>(10);
  return tempList;
}
Run Code Online (Sandbox Code Playgroud)

你可以这样打电话:

var newList = getList<customModel>();
Run Code Online (Sandbox Code Playgroud)

或者在C#3.0之前(在哪里var不可用):

List<customModel> newList = getList<customModel>();
Run Code Online (Sandbox Code Playgroud)

问题是,你可以这样轻松地做到这一点:

var newList = new List<customModel>(10);
Run Code Online (Sandbox Code Playgroud)