C#中关于Action委托的详细信息

6

1)“Action”委托的真正定义是什么?一些定义将其描述为多态条件映射,而另一些则说它是*应用决策表*。

(你可能会问知道定义后能获得什么,如果我知道它,我就能理解它的真实目的)。

2)感谢stackoverflow的Binary Worrier和Andrew Hare提供了很好的例子。当我声明时

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

我能理解它实际上的作用。但当我声明时,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 委托之间的功能差异是什么?


请参见此处的答案:https://dev59.com/DnRB5IYBdhLWcg3wn4jc - BlackTigerX
3个回答

11

这只是另一个委托。 Action<T> 的声明方式如下:

void Action<T>(T item)

它只是“作用于单个项目的东西”。有更多类型参数和普通参数的通用重载。在本身上,Action<T>并不是应用决策表或类似的东西 - 它只是一个委托,可以对项目执行“某些操作”。

字典示例只是一个带有枚举值作为键和操作作为值的字典 - 因此,您可以根据枚举值查找要执行的操作,然后传递User引用以供其处理。

至于Func vs Action vs PredicateFunc类似于Action,但返回值。 Predicate类似,但始终返回bool,而没有范围广泛的通用重载,只有Predicate<T>来确定项目是否“匹配”谓词。


2

1) Action委托

(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”值存储一个方法,其匹配此签名:

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) Action、Function和Predicate的区别: - Action是一个无返回值的方法 - Function是一个有返回值的方法 - Predicate必须返回一个布尔值,并且需要接收1个参数(它基本上回答一个关于接收1个参数的问题的是或否)

希望这可以帮到您。


绝对地,这非常有帮助。 - user193276

2

Action、Func和Predicate具有不同的签名:

void Action<...>(...)
T Func<..., T>(...)
bool Predicate<T>(T)

Action<...>与Func<..., void>相同
Predicate<T>与Func<T, bool>相同


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接