我对 C# 比较陌生。我正在尝试使用
IEnumerable
集合作为 C# 函数的参数,但我也想定义我想要返回的属性。
假设我有一辆汽车
IEnumerable
,具有color
和brand
等属性。当然,每个条目都有颜色和品牌。
我正在尝试拆分有关以下功能的可枚举信息。
这样的事情可能吗?
public string stringforeach(IEnumerable coll, <<color>>, <<brand>>)
{
string write = "";
int i = 0;
foreach (var element in coll)
{
write += string.Concat(i.ToString() + ";" + element.color+ ";" + element.bramd + "\n");
i++;
}
return write;
}
使用 C# 的两个独立功能:
使用 generics 以便该方法可以接受特定类型的集合,编译器知道用于该方法的特定调用的特定类型。
使用 delegates 作为参数,以便能够传递函数(或 lambda 表达式)来指定要访问的对象的哪个属性。
public string StringForeach<T>(IEnumerable<T> coll, Func<T, string> property1, Func<T, string> property2)
{
string write = "";
int i = 0;
foreach (var element in coll)
{
write += i + ";" + property1(element) + ";" + property2(element) + "\n";
i++;
}
return write;
}
给定以下 Car 类
public class Car
{
public string Color { get; set; }
public string Brand { get; set; }
}
你可以这样调用方法:
List<Car> cars = new List<Car>();
cars.Add(new Car { Color = "Red", Brand = "BMW" });
cars.Add(new Car { Color = "Black", Brand = "Mercedes" });
string text = StringForeach<Car>(cars, c => c.Color, c => c.Brand);
一些解释:
public string StringForeach<T>(IEnumerable<T> coll, Func<T, string> property1, Func<T, string> property2)
这声明了一个可以用特定类型 T 调用的泛型方法。它接受三个参数:
IEnumerable<T> coll
:TFunc<T, string> property1
:接受 T 类型参数并返回字符串的函数委托Func<T, string> property2
:见上文。调用方法时
string text = StringForeach<Car>(cars, c => c.Color, c => c.Brand);
我们指定调用类型 T 为具体类型 Car 的方法。
lambda 表达式
c => c.Color
是为此函数编写函数委托的简写形式:
string SomeFunc(Car c)
{
return c.Color;
}
首先需要指定IEnumerable中对象的类型。 IE可数
例如下面的类:
public class itemCar
{
public string color;
public string brand;
public itemCar(string _color, string _brand)
{
this.color = _color;
this.brand = _brand;
}
}
然后,在
stringforeach
函数中,使用 <<color>>, <<brand>> properties
过滤 IEnumerable 并创建所需的输出字符串:
public string stringforeach(IEnumerable<itemCar> coll, string color, string brand)
{
string write = "";
var carFilter= coll.Where(item => item.color == color && item.brand == brand).ToArray();
for (int i= 0; i < carFilter.Length; i++)
write += string.Concat(i.ToString() + ";" + carFilter[i].color + ";" + carFilter[i].brand + "\n");
return write;
}