简体   繁体   English

传递类型参数并声明列表

[英]Pass a type parameter and declare a list

public static List<customModel> getList(type customModel)
{ 
  List<customModel> tempList = new List<customModel>(10);
  return tempList;
}

Is it possible to return a list of type that is passed from somewhere else? 是否可以返回从其他地方传递的类型的列表? I have been doing my own project and notice that if there is any way to do this, my code will be much simpler. 我一直在做自己的项目,请注意,如果有任何方法可以执行此操作,则我的代码将更加简单。

Do you mean by using generics like this: 您是说使用像这样的泛型

public static List<T> getList<T>()
{ 
  List<T> tempList = new List<T>(10);
  return tempList;
}

Which you can call like this: 您可以这样称呼:

var newList = getList<customModel>();

or prior to C# 3.0 (where var is not available): 或C#3.0之前的版本(其中var不可用):

List<customModel> newList = getList<customModel>();

The problem is, you could just as easily do this instead: 问题是,您可以轻松地这样做:

var newList = new List<customModel>(10);

Use a generic: 使用通用:

public static List<T> getList<T>()
{
    return new List<T>(10);
}

Call it like this: 这样称呼它:

var myList = getList<int>();

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

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