创建通用方法 [英] Creating generic method
本文介绍了创建通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以提供以下帮助吗?这让我发疯了……
Can someone please help with the following... it's driving me nuts...
// Three methods, virtually identical with the exception of the select field
public IEnumerable<int> GetBrandID()
{
return myData.Select(m => m.BrandID).Distinct();
}
public IEnumerable<int> GetModelID()
{
return myData.Select(m => m.ModelID).Distinct();
}
public IEnumerable<int> GetVehicleID()
{
return myData.Select(m => m.VehicleID).Distinct();
}
// How to create one method which returns the type specified in the parameter??
public IEnumerable<int> GetData(??? myType)
{
return myData.Select(m => myType).Distinct();
}
推荐答案
听起来您可能只想要一个Func<Model, int>
参数:
It sounds like you probably just want a Func<Model, int>
parameter:
public IEnumerable<int> GetData(Func<Model, int> projection)
{
return myData.Select(projection).Distinct();
}
您可以这样:
var modelIds = GetData(m => m.ModelID);
var vehicleIds = GetData(m => m.VehicleID);
这就是你的追求吗? (假设myData
是IEnumerable<Model>
.如果它是IQueryable<Model>
,则可能要接受Expression<Func<Model, int>>
.)
Is that what you're after? (That's assuming myData
is an IEnumerable<Model>
. If it's an IQueryable<Model>
you may want to accept Expression<Func<Model, int>>
instead.)
这篇关于创建通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文