我想将一个数据集传递给一个函数,但每次都可能不同(但总会实现IEnumerable。所以我对函数的调用将是:
var items = new List<AssetListItem>();
AimsFunctions.dropdown("Asset", "id", items)
或
var items = new List<AssetCategory>();
AimsFunctions.dropdown("Cats", "id", items)
但是我如何在函数中使用它?
public static SelectBox dropdown(string name, string key IEnumerable<T> dataset )
{
// Want to work with dataset with Linq here
}
说它不明白T在IEnumerable中是什么(虽然我也不知道)。
答案 0 :(得分:2)
您尝试使用T
作为类型参数,因此编译器需要知道您的T
。您可能希望使您的方法成为通用方法。修改名称以遵循约定(并且通常更具可读性),您将拥有:
public static SelectBox CreateDropdown<T>(string name, string key, IEnumerable<T> rows)
{
...
}
方法名称后面的<T>
部分表示它是一种通用方法。如果您不熟悉泛型,那么您应该阅读MS guide to generics。
答案 1 :(得分:0)
您的方法需要<T>
是通用的。你可以使用反射,虽然我不喜欢使用它:
public static DropDownList Dropdown<T>(string name, string key, IEnumerable<T> dataset) where T: class
{
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && (p.Name == name || p.Name == key))
.ToArray();
if (properties.Length < 2) throw new ArgumentException("The name and the key properties must exist and the they have to be public");
var nameprop = properties.First(p => p.Name == name);
var keyprop = properties.First(p => p.Name == key);
var data = dataset
.Select(x => new
{
Name = nameprop.GetValue(x, null)?.ToString(),
Key = keyprop.GetValue(x, null)?.ToString(),
})
.ToList();
// use this as datasource for your SelectBox/DropDownList
}