假设我想编写一个扩展方法,将一些数据从T[,]
转储到CSV:
public static void WriteCSVData<T>(this T[,] data, StreamWriter sw)
{
for (int row = 0; row < data.GetLength(0); row++)
for (int col = 0; col < data.GetLength(1); col++)
{
string s = data[row, col].ToString();
if (s.Contains(","))
sw.Write("\"" + s + "\"");
else
sw.Write(s);
if (col < data.GetLength(1) - 1)
sw.Write(",");
else
sw.WriteLine();
}
}
我可以用
打电话using (StreamWriter sw = new StreamWriter("data.csv"))
myData.WriteCSVData(sw);
但假设myData
是Complex[,]
,我想写出复数的大小,而不是完整的值。如果我能写的话会很方便:
using (StreamWriter sw = new StreamWriter("data.csv"))
myData.WriteCSVData(sw, d => d.Magnitude);
但我不确定如何在扩展方法中实现,或者甚至可能实现。
答案 0 :(得分:8)
您可以像这样编写现有方法的重载:
public static void WriteCSVData<T, TValue>(this T[,] data, StreamWriter sw,
Func<T,TValue> func)
{
for (int row = 0; row < data.GetLength(0); row++)
for (int col = 0; col < data.GetLength(1); col++)
{
string s = func(data[row, col]).ToString();
if (s.Contains(","))
sw.Write("\"" + s + "\"");
else
sw.Write(s);
if (col < data.GetLength(1) - 1)
sw.Write(",");
else
sw.WriteLine();
}
}
并按照您想要的方式使用它:
using (StreamWriter sw = new StreamWriter("data.csv"))
myData.WriteCSVData(sw, d => d.Magnitude);
答案 1 :(得分:1)
定义参数类型为 T 的委托,并返回字符串类型。向方法WriteCSVData添加一个参数,类型为委托。
delegate string ExtractValueDelegate<T>(T obj);
public static void WriteCSVData<T>(this T[,] data,ExtractValueDelegte<T> extractor , StreamWriter sw) { ... }
// calling the method
myData.WriteCSVData(sw, d => d.Magnitude.ToString());