[英]c# is it possible to create a delegate like this?
我有一個聽起來像可行的想法,但我不太確定,因此尋求有關是否可以實現以及如何實現的建議。
在我的Web表單上,我有一個名為“錯誤”的布爾值。
要成功加載頁面,需要在頁面上進行很多操作。
我可以這樣寫代碼:
bool thisSuccess = DoThis();
if(!thisSuccess)
then error;
bool thatSuccess = DoThat();
if(!thatSuccess)
then error;
if(error)
FailoverActions();
等等。
當然那將是非常低效的,因此我認為創建某種代碼可能看起來像這樣的委托是可行的:
錯誤= DoThis();
...以及這里的某種觸發器,當error = true時調用了一個函數;
抱歉,沒有確切的細節,但這對我來說是新的基礎。
更新資料
感謝大家的出色創意。
細節很少的原因是我缺乏經驗,並且到目前為止我發現.net的原因是,盡管有很多破解雞蛋的方法,但總的來說有一些更好的方法。
感謝您的寶貴意見。
再次感謝。
為什么不。 返回分配給delegete的布爾值的方法。
這條路
public delegate bool PerformCalculation();
PerformCalculation = DoThis();
if (!PerformCalculation())
then error;
PerformCalculation = DoThat();
if(!PerformCalculation())
then error;
if(error)
FailoverActions();
替代解決方案
無需代表。 只需兩種方法
bool DoThis()
和bool DoThat()
if (!DoThis())
then error;
if(!DoThat())
then error;
if(error)
FailoverActions();
您可以使用Func<bool>
表示初始化步驟:
var steps = new List<Func<bool>>()
{
Step1,
Step2,
Step3
};
其中,Step1等是返回bool
方法。
然后,此循環調用它們:
foreach (var step in steps)
{
if (!step())
{
// an error occurred
break; // use break to exit if necessary
}
}
怎么樣:
public class MyClass
{
private bool _error;
private Func<bool> DoThis;
private Func<bool> DoThat;
public MyClass()
{
DoThis = () => true;
DoThat = () => false;
Validate();
}
public void Validate()
{
Error = DoThis() && DoThat();
}
public bool Error
{
get { return _error; }
set {
_error = value;
if (_error) FailoverActions();
}
}
public void FailoverActions()
{
}
}
首先-讓您的方法返回true
或false
是一種可疑的做法-似乎您應該使用異常來處理此問題,尤其是在錯誤相對較少的情況下。
樣例代碼:
try
{
DoThis();
DoThat();
}
catch(DoingThingsException ex)
{
FailoverActions();
//throw; //?
}
作為一種快速解決方案,一種選擇是短路:
bool success = DoThis() && DoThat() && DoTheOther();
if(!success) FailoverActions();
代表對返回值的行為沒有指定。 例如,如果將多個處理程序分配給一個委托,則使用所使用的返回值之一,但是您無法控制哪個返回值。 這可能導致成功的功能掩蓋某些錯誤的情況。 更不用說呼叫未分配代表的危險了。
有更好的選擇,但是您應該闡明要實現的目標。
您正在描述的內容將適合狀態機設計模式。
可以使用Windows Workflow(實際上包含最新版本的狀態機工作流)對這種事物進行建模。
嘗試這個:
if (!(DoThis() && DoThat()))
then error;
if (error)
FailoverActions();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.