2016-04-20 32 views
1

我檢測到C#的功能,可以像使用事件一樣使用Action或Func。我的意思是,我可以做以下事情:使用Action或Func類似事件 - 不好的做法?

Action aAction; 

aAction = DoSomething; 
aAction += DoAnotherting; 

// execute the action -> both functions will be executed 
aAction(); 

aAction -= DoSomething; // unsubscribe on function 

我沒有意識到這一點,認爲使用+ =只能用於事件。在第一時間,這看起來相當不錯,因爲我不必使用event關鍵字,我也可以從所有者類以外調用此操作(事件不可能)。 但是我想知道,這樣的使用有沒有很好的例子,還是隻是不好的做法?

一個完整的示例如下所示:

[TestMethod] 
public void DummyTest() 
{ 
    DummyClass myInstance = new DummyClass(); 

    int i = 0; 

    Action action1 =() => i++; 
    Action action2 =() => i += 2; 

    Func<int> func1 =() => 5; 

    myInstance.MyFunc +=() => 3; 
    myInstance.MyFunc += func1; 

    Assert.AreEqual(5, myInstance.MyFunc?.Invoke()); 

    myInstance.MyFunc -= func1; 

    Assert.AreEqual(3, myInstance.MyFunc?.Invoke()); 

    myInstance.MyAction = action1; 
    myInstance.MyAction += action2; 

    myInstance.MyAction?.Invoke(); 

    Assert.AreEqual(3, i); 
    myInstance.MyAction -= action1; 

    myInstance.MyAction?.Invoke(); 

    Assert.AreEqual(5, i); 

    myInstance.MyAction =() => i = 0; 

    myInstance.MyAction?.Invoke(); 

    Assert.AreEqual(0, i); 
} 


class DummyClass 
{ 
    public Action MyAction; 
    public Func<int> MyFunc; 
} 
+0

不是。看看這裏:[行動](http://stackoverflow.com/questions/7408744/is-it-bad-practice-to-use-action-and-func-all-the-time-instead-of-making-corresp ) –

+0

我想引用NodaTime格式器。我已經在這裏提取摘錄:https://gist.github.com/Feanathiel/38fbcace35bc3f4f2d48(基於https://github.com/nodatime/nodatime/blob/69a2cdad9cb4c32a82620eae4f2460ff9479570a/src/NodaTime/Text/Patterns/SteppedPatternBuilder。 CS) – Caramiriel

+0

這個問題可能更適合http://programmers.stackexchange.com/ – AlexFoxGill

回答

1

這是我印象中的event這纔是重點是把事件控制進入封閉類型。當事件被解僱時,客戶無法選擇。一個事件是一個(集合)函數,當一些狀態在某種類型中被改變時,或者當某些有趣的事情發生時,客戶端可能會對此作出反應,但是這些(或者)函數將被調用,但是確切的細節應該隱藏同樣的原因,你不應該暴露給客戶的領域。

從它意味着炸燬你的房子的意義上說,它沒有任何內在的可怕性,但另一方面沒有理由使用它們。事件有語言的原因,它們具有語義意義。如果您使用Action/Func代表而不是事件,那麼讀取代碼的人將必須弄清楚您正在做什麼,以及爲什麼您不使用傳統工具。這只是混亂/噪音,所以我的建議是避免它。

+0

感謝您的評論,與我正在考慮這個問題一樣。我的問題的原因是,我參觀了軟件培訓,培訓師以這種方式採取了行動。我在想,這有什麼好處。不幸的是,培訓師無法回答我的問題...... – user2959547

+0

是的......我們不應該使用我們自己的複雜類/對象......因爲它可能讓其他人感到困惑...... –

相關問題