我在使用 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委托和 Func 委托是相同的。我只是将Func委托复制到DelegateOrder委托。
在上面的代码示例中,该行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.