简体   繁体   English

C#2中的代理人/匿名方法

[英]Delegates/Anonymous Method in C# 2

In C# 1. You don't have delegate sorting or comparison options. 在C#1中。您没有委托排序或比较选项。 You might be forced to do it by creating another type which implements IComparer to sort your collections in ArrayList. 您可能被迫通过创建另一个实现IComparer的类型来对它进行排序,以对ArrayList中的集合进行排序。 But starting from c# 2. You can use delegates for your comparisons. 但是从c#2开始。您可以使用委托进行比较。 Look the following example. 看下面的例子。

List<Product> products = Product.GetSampleProducts();
products.sort(delegate(Product p1, Product p2) {return p1.Name.CompareTo(p2.Name);});

I can see 我可以看到
1) how the delegate (Anonymous Method) makes life easy 1)委托(匿名方法)如何使生活变得轻松
2) how the code becomes readable and how it helped me do the Comparison with out creating another type. 2)代码如何变得易读以及如何帮助我进行比较而无需创建其他类型。

My question is - What if we want to use this comparison in Multiple areas in my application? 我的问题是-如果我们想在我的应用程序的多个区域中使用此比较? don't you think this will force me to write the same "Anonymous Method" again and again? 您不认为这会迫使我一次又一次地写同样的“匿名方法”吗? Don't you think this is against the OOP of re-usability? 您是否不认为这违反了可重复使用的OOP?

If you're using the same anonymous method over and over, it should probably be a static method somewhere. 如果您一遍又一遍地使用相同的匿名方法,那么它在某处可能应该是静态方法。 Then you just pass a reference to that instead of the delegate. 然后,您只需传递对该引用的引用即可,而不是委托。 Anonymous delegates should be for one-offs, perhaps because it needs a reference to closure variables/parameters. 匿名委托应该是一次性的,也许是因为它需要引用闭包变量/参数。

If you reuse a piece of code frequently, refactor it into its own method. 如果您经常重复使用一段代码,请将其重构为自己的方法。

As you suggest, repeating a chunk of code does go against reusability. 正如您所建议的那样,重复执行一段代码确实会损害可重用性。 I can't think of a pattern that would make you do that. 我想不出一种可以使您做到这一点的模式。

Action reusableFunc = () => Console.WriteLine("Hello, world!");

somewhere: 某处:

reusableFunc();

elsewhere: 别处:

reusableFunc();

Something in between should do it 两者之间应该做些什么

delegate void MyDelegate(Product p1, Product p2);

MyDelegate myDelegate = delegate(Product p1, Product p2e) { 
    return p1.Name.CompareTo(p2.Name);
};

products.sort(myDelegate);
products2.sort(myDelegate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM