【问题标题】:How to create List<T> instance in C# file如何在 C# 文件中创建 List<T> 实例
【发布时间】:2019-11-27 19:58:20
【问题描述】:

我有这些课程:

public class BaseGrid
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public int total { get; set; }
    public List<T> rows { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

回到我的控制器,我想做一些类似的事情:

        List<Product> listOfProducts = new List<Product>();

        BaseGrid baseGrid = new BaseGrid();
        baseGrid.rowCount = 10;
        baseGrid.total = 20;
        baseGrid.current = 1;
        baseGrid.rows = listOfProducts;

如何将“行”属性变成一个通用列表,例如在 runtime 中将 baseGrid.rows 转换为我想要的任何列表类型?

谢谢。

【问题讨论】:

  • 提示:BaseGrid 需要是通用的。
  • @Amy:泛型是一个编译时概念,即使您指定具体类型也是如此。
  • @RobertHarvey 我知道。我认为你和我对这个问题的解释非常不同。

标签: c# list generics reflection


【解决方案1】:
 public class BaseGrid<T> where T : class
{
    public int current { get; set; }
    public int rowCount { get; set; }
    public int total { get; set; }
    public List<T> rows { get; set; }
}

【讨论】:

  • 如果没有定义任何其他构造函数,则不需要显式声明泛型构造函数。
  • @nulltron:你还需要初始化列表。
  • @RobertHarvey 我没有意识到你在谈论列表哈哈
  • 好吧,否则你为什么还要费心把它变成通用的呢? :)
  • @RobertHarvey 因为泛型很棒
【解决方案2】:

听起来你想要的是运行时多态性。

public abstract class Animal
{
  public abstract void makeSound()
  {
    Console.WriteLine("[nothing happens]");
  }
}

public class Cat : Animal
{
  public override void makeSound()
  {
    Console.WriteLine("Meow");
  }
}

public class Dog : Animal
{
  public override void makeSound()
  {
    Console.WriteLine("Woof");
  }
}

public static void main(String[] args) 
{
    var animals = new List<Animal>();
    animals.Add(new Dog());
    animals.Add(new Cat());
    Console.Add(animals[0].MakeSound());  // Woof
    Console.Add(animals[1].MakeSound());  // Meow
}

【讨论】:

    猜你喜欢
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    相关资源
    最近更新 更多