我迷失在這里關于傳遞函式的許多答案和示例(使用 C# 將方法作為引數傳遞)。
目前我有這個:
private void AddWeekToHistory(ref XDocument xdoc, MSAHistoryWeek historyWeek)
{
// Do stuff
DetectStudentItemDescriptionAndType(studentItem,
bFirstStudent,
iClass,
out string strDesc,
out string strType);
// Do stuff
}
private void DetectStudentItemDescriptionAndType(MSAHistoryItemStudent studentItem, bool bFirstStudent, int iClass, out string strDesc, out string strType)
{
// Do stuff
}
我想進行更改AddWeekToHistory,以便可以將其傳遞給DetectStudentItemDescriptionAndType函式。這是因為我想添加該函式的第二個版本,它將使用不同的邏輯(相同的引數)。
最終我想打電話AddWeekToHistory(ref xdoc, historyWeek, [name-of-func]);。
我從答案中了解到,由于我使用的void是我應該使用的功能Action。但是我迷失了答案,因為原始問題中的方法傳遞了一個引數,但在運行傳遞函式的示例中,它們實際上并沒有傳遞引數。
因此,我沒有混淆現有問題,而是提出了一個新問題。我需要進行哪些更改才能支持將傳遞DetectStudentItemDescriptionAndType及其變體(相同屬性)作為函式來傳遞AddWeekToHistory?
uj5u.com熱心網友回復:
您不能將任何Action<...>委托用于帶有ref或out引數的方法。您將需要一個自定義委托:
public delegate void DetectStudentItemDescriptionAndTypeDelegate(MSAHistoryItemStudent studentItem, bool bFirstStudent, int iClass, out string strDesc, out string strType);
private void AddWeekToHistory(ref XDocument xdoc, MSAHistoryWeek historyWeek, DetectStudentItemDescriptionAndTypeDelegate detect)
{
// Do stuff
detect(studentItem,
bFirstStudent,
iClass,
out string strDesc,
out string strType);
// Do stuff
}
private void DetectStudentItemDescriptionAndType(MSAHistoryItemStudent studentItem, bool bFirstStudent, int iClass, out string strDesc, out string strType)
{
// Do stuff
}
AddWeekToHistory(xdoc, historyWeek, DetectStudentItemDescriptionAndType);
代表 - C# 編程指南
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414344.html
標籤:
上一篇:如何在python模塊中重用函式
