C#代表真实世界的用法 [英] C# Delegates Real World Usage
问题描述
我previously问有关委托的问题没有任何人有一个必须具备的场景,我就必须使用委托?这是如何提高我的C#code?
I've previously asked a question of about Delegates does anyone have a must have scenario where I would have to use a delegate? How does this improve my C# code?
就在很多情况下我用它在我似乎总是能围绕它进行编程。
Just as many scenarios I use it in I've always seem to be able to program around it.
推荐答案
假设你不是在谈论事件 - 当然,你可以围绕它的方案。问题的关键是让它的更好和清洁
Assuming you're not talking about events - of course you can program around it. The point is to make it nicer and cleaner.
protected void Sort()
{
foreach (string key in _dBase.Keys)
{
Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key],
new Comparison<Pair<string, Dictionary<string, T>>>(
delegate(Pair<string, Dictionary<string, T>> a, Pair<string, Dictionary<string, T>> b)
{
if (a == null && b != null)
return 1;
else if (a != null && b == null)
return -1;
else if (a == null && b == null)
return 0;
else
return a.First.CompareTo(b.First);
}));
}
}
我可以做,没有一个内联委托?当然。我会在我的课软盘私有方法,只会被用于这一个实例?是啊。
Could I do that without an inline delegate? Sure. Would I have a floppy private method in my class that would only be used for this one instance? Yup.
编辑:正如在评论中提到,您可以简化:
As mentioned in the comments, you can simplify:
Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key],
new Comparison<Pair<string, Dictionary<string, T>>>(
delegate(Pair<string, Dictionary<string, T>> a, Pair<string, Dictionary<string, T>> b)
{
到
Array.Sort<Pair<string, Dictionary<string, T>>>(_dBase[key], (a,b) =>
{
这篇关于C#代表真实世界的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!