【问题标题】:How to get the value from Generic<T> in foreach loop如何在 foreach 循环中从 Generic<T> 获取值
【发布时间】:2019-06-26 05:26:03
【问题描述】:

我创建了一个支持所有类模型的函数(通用)。但我有一个关于为每个循环获取泛型值的查询。

这是针对 ASP.NET (MVC),在控制器中创建的代码。

public List<SelectListItem> GetGenericList<T> (list<T> genModel)
{
List<SelectListItem> lst =  new List<SelectListItem>();
foreach(var dyn in lst)
{
    lst.add (new selectlistitem
    {
        text = dyn.??,
        Value = dyn.??
    });
}

}

  1. 如果我将员工类模型传递给此函数,我想访问属性名称,例如“文本”的 empid 和“值”的 empname。
  2. 如果我将学生类模型传递给此函数,我想访问属性名称,例如“文本”的 studentid 和“值”的 studentname。

【问题讨论】:

  • 你在哪里使用过genModel
  • 你不需要泛型。您可以使用 Id 和 Name 属性创建一个名为 IModelInterface (或类似的东西..)的接口。在您的类(学生和员工)中实现该接口。将接口参数传递给 GetList 方法。循环时,您只需使用 dyn.Id 和 dyn.Name
  • SelectListItem 有属性TextValue,你有什么问题?
  • 另外,请确保您提供的代码能够编译。
  • 另外,您的foreach 甚至不会运行一个循环。

标签: c# list function generics foreach


【解决方案1】:

您可以这样做的一种方法是向您的方法添加另外两个参数 - 一个文本选择器和一个值选择器:

public List<SelectListItem> GetGenericList<T> (list<T> genModel, Func<T, string> textSelector, Func<T, string> valueSelector)
{
    List<SelectListItem> lst =  new List<SelectListItem>();
    // loop through genModel, not lst!
    foreach(var model in genModel)
    {
        lst.add (new SelectListItem
        {
            Text = textSelector(model), // Note how we use the selectors here
            Value = valueSelector(model)
        });
    }
    return lst;
}

要将此方法用于Employee,您可以这样操作:

GetGenericList(someEmployeeList, x => x.empid, x => x.empname);

对于Student,你可以dp:

GetGenericList(someStudentList, x => x.studentid, x => x.studentname);

【讨论】:

    【解决方案2】:

    您不需要为此要求实施Generics。您所要做的就是在您的班级之间有一个默认的“经纪人”。

    只需为您的模型创建一个通用接口

    interface IModelInterface
    {
        int Id { get; set; }
        string Name { get; set; }
    }
    

    你的类应该实现接口为

        public class Student : IModelInterface
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class Employee : IModelInterface
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    对您的 GetGenericList 方法稍作改动

     public List<SelectListItem> GetListItems(List<IModelInterface> genModel)
        {
            List<SelectListItem> lst = new List<SelectListItem>();
            foreach (var dyn in genModel)
            {
                lst.Add(new SelectListItem
                {
                    Text = dyn.Name,
                    Value = Convert.ToString(dyn.Id)
                });
            }
    
            return lst;
        }
    

    有多种方法可以实现这一点。我只是给了你其中一个答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2017-05-18
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多