C# 如何获取Func的键<;Q、 字符串>;基于字符串键
我试图编写一个通用方法来获取排序键以执行C# 如何获取Func的键<;Q、 字符串>;基于字符串键,c#,linq,c#-4.0,func,c#-6.0,C#,Linq,C# 4.0,Func,C# 6.0,我试图编写一个通用方法来获取排序键以执行OrderBy操作,但在下面的代码中失败了 public Func<Q, string> GetSortProperty<Q>(IQueryable<Q> data, string SortColumn) { if (!string.IsNullOrWhiteSpace(sortColumn)) { Func<Q, string> sort = i => i.GetTy
OrderBy
操作,但在下面的代码中失败了
public Func<Q, string> GetSortProperty<Q>(IQueryable<Q> data, string SortColumn)
{
if (!string.IsNullOrWhiteSpace(sortColumn))
{
Func<Q, string> sort = i => i.GetType().GetProperty(sortColumn).GetValue(i, null);
return sort;
}
return null;
}
public Func GetSortProperty(IQueryable数据,字符串SortColumn)
{
如果(!string.IsNullOrWhiteSpace(sortColumn))
{
Func sort=i=>i.GetType().GetProperty(sortColumn).GetValue(i,null);
返回排序;
}
返回null;
}
我审问了以下问题
请帮助我。基于
GetValue
声明:
public virtual object GetValue(object obj, object[] index);
您可以将方法的类型从Func
更改为Func
:
另外,如果您正在使用C#6,我建议您这样更改它,以防止出现NullReferenceException
:
Func<Q, string> sort = i => (string)i.GetType().GetProperty(SortColumn)?.GetValue(i, null);
Func sort=i=>(字符串)i.GetType().GetProperty(SortColumn)?.GetValue(i,null);
基于GetValue
声明:
public virtual object GetValue(object obj, object[] index);
您可以将方法的类型从Func
更改为Func
:
另外,如果您正在使用C#6,我建议您这样更改它,以防止出现NullReferenceException
:
Func<Q, string> sort = i => (string)i.GetType().GetProperty(SortColumn)?.GetValue(i, null);
Func sort=i=>(字符串)i.GetType().GetProperty(SortColumn)?.GetValue(i,null);