我在使用 Delegate 和 OrderBy 扩展方法时遇到了问题。 谁能告诉我为什么?提前致谢。 以下是完整代码:
namespace StudyDemo
{
public class MyDelegate
{
public delegate TResult DelegateOrder<in T, out TResult>(T arg);
}
public class Product
{
public string Name { get; private set; }
public decimal? Price { get; set; }
public Product(string name, decimal price)
{
Name = name;
Price = price;
}
/* private parameterless constructor for the sake of the new property-based initialization. */
Product() { }
public static List<Product> GetSampleProducts()
{
return new List<Product>
{
new Product { Name="West Side Story", Price=9.99m },
new Product { Name="Assassins", Price=14.99m },
new Product { Name="Frogs", Price=13.99m },
new Product { Name="Sweeney Todd", Price=10.99m }
};
}
public override string ToString()
{
return string.Format("{0}: {1}", Name, Price);
}
}
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
public string myOrder(Product p)
{
return p.Name;
}
private void button2_Click(object sender, EventArgs e)
{
List<Product> products = Product.GetSampleProducts();
Func<Product, string> orderDelegate2 = myOrder;
foreach (Product product in products.OrderBy(orderDelegate2))
{
/* Do something */
}
MyDelegate.DelegateOrder<Product, string> myOrder2 = myOrder;
foreach (Product product in products.OrderBy(myOrder2)) /* not functioning, why? */
{
/* Do something */
}
}
}
}
注释如下: DelegateOrder委托(delegate)和Func委托(delegate)是一样的。 我只是将 Func 委托(delegate)复制到 DelegateOrder 委托(delegate)。
在上面的代码示例中,行 foreach (Product product in products.OrderBy(myOrder2)) 无法正常工作,谁能告诉我为什么?
这是编译代码时的错误:
The type arguments for method 'System.Linq.Enumerable.OrderBy<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
请您参考如下方法:
编译器无法将您的自定义委托(delegate)类型 DelegateOrder 转换为 System.Func(这是 IEnumerable.OrderBy 所需的参数)。
尽管事实上两者本质上具有相同的签名。首选使用 System.Func,因为它提供了具有相同签名的委托(delegate)之间的互操作。
如果我是你,我会简单地使用一个内联匿名函数来处理排序:
foreach(Product product in products.OrderBy((Product source)=>source.Name))
{
// Do something...
}
有趣的是 - 对于奖励积分 - 如果您确实想使用委托(delegate)对象,则以下方法可行:
foreach(Product product in products.OrderBy((x)=>myOrder2(x)))
{
// Do something...
}
