2009-10-22 38 views
6

的詳細信息1)什麼是行動委託的真正定義?一些定義描述爲:多態條件圖,有人說它*應用決策表*。有關行動委託在C#

你可能會問,如果我知道它,我可以瞭解它的真正目的,通過了解定義,你將獲得什麼)

2)感謝Binaryflow的Andrew Hare給出了很好的例子。 當我宣佈

string[] words = "This is as easy as it looks".Split(' '); 
`Array.ForEach(words, p => Console.WriteLine(p));` 

我能理解它實際上does.But當我宣佈,如何C#解釋時,我 聲明

 Dictionary<SomeEnum, Action<User>> methodList = 
    new Dictionary<SomeEnum, Action<User>>() 
    methodList.Add(SomeEnum.One, DoSomething); 
    methodList.Add(SomeEnum.Two, DoSomethingElse); 

它存放在字典中操作的集合?。遺憾作爲例子是不完整的,我沒有得到它。

3)Action , Function ,Predicate delagets之間的功能區別是什麼?

+0

在這裏看到答案http://stackoverflow.com/questions/566860/delegates-predicate-action-func – BlackTigerX

回答

11

這只是另一個代表。 Action<T>聲明如下:

void Action<T>(T item) 

這只是「東西作用於單個項目」。有更多類型參數和常規參數的泛型重載。本身,Action<T>不是一個應用決策表或類似的東西 - 它只是一個可以對某個項目做「某事」的委託。

字典示例僅僅是一個字典枚舉值爲鍵和作爲值的操作 - 因此您可以查找基於枚舉值的操作,然後傳入User引用以供其執行。

至於Func vs Action vs PredicateFunc就像Action,但返回一個值。 Predicate與此類似,但始終返回bool,並且沒有泛型重載的範圍,只是Predicate<T>來確定項目是否與謂詞「匹配」。

2

行動,Func鍵和謂語具有不同的簽名:

無效動作<...>(...)
牛逼Func鍵< ...,T >(...)
布爾謂詞< Ť>(T)

動作<...>相同函數功能< ...,空隙>
謂詞<Ť>與Func < T相同,bool >

2

1)行動代表

(Action, Action<T>, Action<T, T2> ...) 

是通用的委託,以避免在應用程序中的許多委託創作的。我們的想法是:

//- Action => void method with 0 args 
//- Action<T> => void method with 1 arg of type T 
//- Action<T, T2> => void method with 2 args of type T et T2 
//... 

2)字典中存儲用於每個 'SomeEnum' 值,一種方法wicth匹配這個簽名:

void MethodExample (User arg); 

下面是一個例子:

public Init() { 
    deleteUserMethodsByStatus = new Dictionary<SomeEnum, Action<User>>(); 
    deleteUserMethodsByStatus.Add(UserStatus.Active, user => { throw new BusinessException("Cannot delete an active user."); }); 
    deleteUserMethodsByStatus.Add(UserStatus.InActive, DoUserDeletion}); 
} 

//This is how you could use this dictionary 
public void DeleteUser(int userId) { 
    User u = DaoFactory.User.GetById(userId); 
    deleteUserMethodsByStatus[u.Status](u); 
} 

//the actual deletion process 
protected internal DoUserDeletion(User u) { 
    DaoFactory.User.Delete(u); 
} 

3 )動作,函數,謂詞之間的區別: - 動作是無效方法(無返回值) - 函數是非void方法(具有返回值) - 謂詞必須返回一個布爾值並取1個參數(它基本上回答是或否,以獲取1個參數的問題)

我希望這可以幫到你。

+0

Absoultely它是非常有用的 – user193276