【问题标题】:Generic ASP.NET MVC method that can be called on any model type可在任何模型类型上调用的通用 ASP.NET MVC 方法
【发布时间】:2021-07-23 22:38:20
【问题描述】:

我想编写一个函数,该函数可以从我的 HomeController 在 List 上调用,其类型是我的任何具有彼此数据类型的模型。目标是还传入我知道存在的各种列名,并在遍历列表时对这些列进行操作。

目前,我遇到的问题是,当我尝试使用传入的列名参数对某个索引处的列表进行操作时,C# 给我一个错误,即我输入的列类型项目对于泛型类型的 List,我不存在传入,而实际上我会保证作为字符串传入的列存在。

通用代码如下:

public static void someOperation<T>(List<T> itemList, string colName1, string colName2) {
    for (int i = 0; i < itemList.Count; i++) {
        float newItem = ((float)itemList[i].colName1) // the variable colName1 in my list of objects is a float
    }
}

如果有更好的方法来编写可以在我的 MVC 结构中的任何类型模型的 List 上执行的函数,请告诉我。

【问题讨论】:

    标签: c# asp.net asp.net-mvc generics


    【解决方案1】:

    您需要添加一个约束,告诉编译器该属性属于该类型

    public static void someOperation<T>(List<T> itemList, string colName1, string colName2) where T : MyItem 
    {
        for (int i = 0; i < itemList.Count; i++) {
           float newItem = itemList[i].colName1;
        }
    }
    
    public class MyItem 
    {
        public float colName1 { get; set; }
    }
    
    public class Model1 : MyItem
    {
    }
    
    public class Model2 : MyItem
    {
    }
    

    【讨论】:

    • 感谢您的回复。这样做不会破坏传递通用列表的目的吗?我必须为我的每个模型类型都有一个单独的函数,我说“where T : ModelType”,这是我试图避免的。
    • 如果你所有的模型都有相同的属性名,它们都可以实现MyItem,所以你可以用一个函数来做所有的事情。更新了上面的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-05-30
    • 2011-07-15
    • 2013-08-29
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多