[英]C# Passing Generic Class as a parameter to a custom Method
I'm trying to create a generic function that can take in the following parameters. 我正在尝试创建一个可以接受以下参数的通用函数。
Below is an example of the function that I'm trying to replicate. 下面是我要复制的函数的示例。
public List<T> GetDataPerPage<T>(IList<T> classType, int pageNum, int pageSize, string orderByColumn)
{
if (pageSize <= 0) pageSize = 10; // TODO: Default pageSize for the Moment
if (pageNum <= 0) pageNum = 1;
int excludedRows = (pageNum - 1) * pageSize;
return GetRepo<classType>().All(null).AsQueryable().Where(p => p.IsDeleted == false).OrderBy(p => p.orderByColumn).Skip(excludedRows).Take(pageSize).ToList();
}
I'm uncertain of how it should pass the classType and the orderByColumn to the function. 我不确定如何将classType和orderByColumn传递给函数。
Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks
谢谢
You do not need to pass the classType
parameter at all, because you will declare the type T
when you use the GetDataPerPage<T>()
method, so change it to this: 您根本不需要传递
classType
参数,因为使用GetDataPerPage<T>()
方法时将声明类型T
,因此将其更改为:
public List<T> GetDataPerPage<T>(int pageNum, int pageSize, string orderByColumn)
{
if (pageSize <= 0) pageSize = 10; // TODO: Default pageSize for the Moment
if (pageNum <= 0) pageNum = 1;
int excludedRows = (pageNum - 1) * pageSize;
return GetRepo<T>().All(null)
.AsQueryable()
.Where(p => p.IsDeleted == false)
.OrderBy(p => p.orderByColumn)
.Skip(excludedRows)
.Take(pageSize)
.ToList();
}
As for the orderByColumn
parameter, if you are going to just do a comparison like your example, then passing in a string
is fine, but if you want to control the logic of the comparison to use a string
property of type T
, then pass a delegate like this: 至于
orderByColumn
参数,如果您要像示例一样进行比较,则可以传入一个string
,但是如果您想控制比较的逻辑以使用类型为T
的string
属性,则可以传递一个这样的代表:
public List<T> GetDataPerPage<T>(int pageNum, int pageSize, Func<T, string> orderBy)
{
if (pageSize <= 0) pageSize = 10; // TODO: Default pageSize for the Moment
if (pageNum <= 0) pageNum = 1;
int excludedRows = (pageNum - 1) * pageSize;
return GetRepo<T>().All(null)
.AsQueryable()
.Where(p => p.IsDeleted == false)
.OrderBy(orderBy)
.Skip(excludedRows)
.Take(pageSize)
.ToList();
}
Usage: 用法:
var list = GetDataPerPage<T>(pageNum, pageSize, p => p.Property1);
You already know the "class type".. its T
: 您已经知道“类类型” ..它的
T
:
GetRepo<T>().All(null)...
For the OrderBy
.. pass in a delegate yourself: 对于
OrderBy
..自己传递一个委托:
public List<T> GetDataPerPage<T>(IList<T> classType,
int pageNum,
int pageSize,
Func<T, object> orderBy)
{
...
return ... ... .OrderBy(orderBy)
}
And pass the delegate in like this: 然后像这样传递委托:
GetDataPerPage(..., ..., ..., x => x.SomePropertyHere);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.