我试图解决的问题是如何编写一个方法,该方法将属性名称作为字符串,并返回分配给所述属性的值.
我的模型类声明类似于:
public class Foo
{
public int FooId
public int param1
public double param2
}
Run Code Online (Sandbox Code Playgroud)
从我的方法中,我希望做一些类似的事情
var property = GetProperty("param1)
var property2 = GetProperty("param2")
Run Code Online (Sandbox Code Playgroud)
我目前正在尝试使用表达式,如
public dynamic GetProperty(string _propertyName)
{
var currentVariables = m_context.Foo.OrderByDescending(x => x.FooId).FirstOrDefault();
var parameter = Expression.Parameter(typeof(Foo), "Foo");
var property = Expression.Property(parameter, _propertyName);
var lambda = Expression.Lambda<Func<GlobalVariableSet, bool>>(parameter);
}
Run Code Online (Sandbox Code Playgroud)
这种方法是否正确,如果是这样,是否可以将其作为动态类型返回?
答案是正确的,这使得这太复杂了.解决方案现在是:
public dynamic GetProperty(string _propertyName)
{
var currentVariables = m_context.Foo.OrderByDescending(g => g.FooId).FirstOrDefault();
return currentVariables.GetType().GetProperty(_propertyName).GetValue(currentVariables, null);
}
Run Code Online (Sandbox Code Playgroud) 我想创建一种动态方式来返回按参数 xy 排序的列表。该列表可以按降序、升序、ID、用户名、邮件等排序。
我以字符串形式接收此参数。所以例如sort=-username
减号表示列表降序。排序参数是用户名。
所以我回来了 user.OrderByDescending(o => o.Username).ToList();
目前,在长 if-else 构造的帮助下,我检测到需要哪种排序。
我希望我可以在对象参数的函数的帮助下替换排序字符串参数。
伪代码
//input for example: sort=-username
Boolean isAscending = isAscending(sort) //return true or false
var parameter = isSortStringInsideObject(sort) //
if (isAscending) {
user.OrderBy(o => o.parameter).ToList();
} else {
user.OrderByDescending(o => o.parameter).ToList();
}
Run Code Online (Sandbox Code Playgroud)
所以参数可以是对象中的每个参数。
我是 .net 核心的新手。所以我希望我没有制定一个乌托邦式的要求。