C# 2 中的委托/匿名方法

发布于 2024-09-26 23:08:43 字数 454 浏览 6 评论 0原文

在 C# 中 1. 您没有委托排序或比较选项。您可能被迫通过创建另一种实现 IComparer 的类型来对 ArrayList 中的集合进行排序。 但从 c# 2 开始。您可以使用委托进行比较。看下面的例子。

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

我能看到
1) 委托(匿名方法)如何让生活变得轻松
2)代码如何变得可读以及它如何帮助我在不创建另一种类型的情况下进行比较。

我的问题是 - 如果我们想在我的应用程序的多个区域中使用此比较怎么办?你不认为这会迫使我一次又一次地写同样的“匿名方法”吗? 您不认为这违背了可重用性的 OOP 吗?

In C# 1. You don't have delegate sorting or comparison options. You might be forced to do it by creating another type which implements IComparer to sort your collections in ArrayList.
But starting from c# 2. You can use delegates for your comparisons. 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
2) how the code becomes readable and how it helped me do the Comparison with out creating another type.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

同展鸳鸯锦 2024-10-03 23:08:43

如果您一遍又一遍地使用相同的匿名方法,它可能应该是某个地方的静态方法。然后您只需传递对此的引用而不是委托。匿名委托应该是一次性的,也许是因为它需要对闭包变量/参数的引用。

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.

三生殊途 2024-10-03 23:08:43

如果你经常重用一段代码,请将其重构为自己的方法。

正如您所建议的,重复一段代码确实不利于可重用性。我想不出有什么模式可以让你这样做。

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.

铜锣湾横着走 2024-10-03 23:08:43
Action reusableFunc = () => Console.WriteLine("Hello, world!");

某处:

reusableFunc();

其他地方:

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

somewhere:

reusableFunc();

elsewhere:

reusableFunc();
贪了杯 2024-10-03 23:08:43

介于两者之间的东西应该可以做到

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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文