C#按属性名称动态访问属性值

The*_*ads 14 c# lambda dynamic

我试图解决的问题是如何编写一个方法,该方法将属性名称作为字符串,并返回分配给所述属性的值.

我的模型类声明类似于:

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)

Dzm*_*voi 26

public static object ReflectPropertyValue(object source, string property)
{
     return source.GetType().GetProperty(property).GetValue(source, null);
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*rov 6

您将使用您提供的样品落伍.

您正在寻找的方法:

public static object GetPropValue( object target, string propName )
 {
     return target.GetType().GetProperty( propName ).GetValue(target, null);
 }
Run Code Online (Sandbox Code Playgroud)

但是使用"var"和"dynamic","Expression"和"Lambda"......你必须在6个月后迷失在这段代码中.坚持简单的写作方式