我已经创建了这个有一个扩展方法的帮助类RichTextBoxHelper,我想编写另一个WriteLine方法或重写这个方法(哪个解决方案最好),以便能够在它下面显示的函数中使用它。谢谢。
public static class RichTextBoxHelper
{
public static void WriteLine(this RichTextBox txtLog, object line)
{
txtLog.AppendText(line + Environment.NewLine);
}
}
private void selectToolStripMenuItem_Click(object sender, EventArgs e)
{
var vehicles = new List<Tuple<string, string, int>>
{
Tuple.Create("123","VW",1999),
Tuple.Create("234","Ford",2009),
Tuple.Create("567","Audi",2005),
Tuple.Create("678","Ford",2003),
Tuple.Create("789","Mazda",2003),
Tuple.Create("999","Ford",1965)
};
var fordCars = vehicles.Where(v => v.Item2 == "Ford")
.Select(v => new Car
{
VIN = v.Item1,
Make = v.Item2,
Year = v.Item3
});
foreach (var item in fordCars)
txtLog.WriteLine("Car VIN:{0} Make:{1} Year:{2}", item.VIN, item.Make, item.Year);
}
答案 0 :(得分:4)
新方法所需的签名是:
public static void WriteLine(
this RichTextBox txtLog,
string format,
params object[] args)
{
// ...
}
只需将它与其他类放在同一个类中,您就可以在适当的时候使用它们。
或者,您可以通过以下方式调用现有方法:
txtLog.WriteLine(
String.Format(
"Car VIN:{0} Make:{1} Year:{2}",
item.VIN,
item.Make,
item.Year));
答案 1 :(得分:0)
我认为dav_i答案是正确的,但我更希望您为IsIn方法编写扩展方法,如下所示,因为您可以在各处将其用于各种不同类型的变量:
public static class ExtensionMethods
{
public static bool IsIn<T>(this T keyObject, params object[] collection)
{
return collection.Contains(keyObject);
}
}
方法的用法如下:
if (intValue.IsIn( 2, 3, 7 ))
{
do something...
}
if (stringVlaue.IsIn("a","b","c"))
{
do something...
}