[英]pass datatype of custom entity into function c#
我有四種不同的數據類型,都作為列表:
List<DataRowTenant> tenantlist;
List<DataRowOwner> ownerlist;
List<DataRowCustomer> customerlist;
List<DataRowHWDevice> hwdevicelist;
List<DataRowHWCategory> hwcategorslist;
我希望能夠將它們導出到 CSV 中。 目前我復制了我的 CSV-export Function 五次,只是使用了不同的名稱和參數定義。 所以,我問自己是否可以以某種方式識別變量的數據類型並將其傳遞到 function 中?
我已經嘗試過這個Thread中的方法,但我無法讓它工作。
我的 CSV 導出 function 如下:
public static void ExportOwnerCSV(List<DataRowOwner> list)
{
string columnNames = "";
string[] outputCsv = new string[list.Count + 1];
if (list.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "Output.csv";
bool fileError = false;
bool? result = sfd.ShowDialog();
if (result == true)
{
if (File.Exists(sfd.FileName))
{
try
{
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
if (!fileError)
{
try
{
//var columnCount = DataRowOwner.GetType().GetFields();
var list_single = list[0];
var columnCount = list_single.GetType().GetProperties(BindingFlags.DeclaredOnly |
BindingFlags.Public |
BindingFlags.Instance);
//Header schreiben
foreach (PropertyInfo item in columnCount)
{
outputCsv[0] += "\"" + item.Name + "\"" + ",";
}
//Body schreiben
int row = 1;
foreach (var DataRowitem in list)
{
foreach (PropertyInfo item in columnCount)
{
outputCsv[row] += "\"" + item.GetValue(list[row - 1]) + "\"" + ",";
}
row++;
}
File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
MessageBox.Show("Data Exported Successfully!", "Info");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("No Record To Export!", "Info");
}
}
謝謝,任何建議表示贊賞。
您可以將 function 聲明為通用 function,其中 function 的類型參數用作列表參數的類型參數,如下所示:
public static void ExportOwnerCSV<T>(IList<T> list)
{
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.