C# accessing property values dynamically by property name

帅比萌擦擦* 提交于 2019-12-18 14:45:16

问题


The problem I am trying to solve is how to write a method which takes in a property name as a string, and returns the value assigned to said property.

My model class is declared similar to:

public class Foo
{
    public int FooId
    public int param1
    public double param2
}

and from within my method I wish to do something similar to this

var property = GetProperty("param1)
var property2 = GetProperty("param2")

I am currently trying to do this by using Expressions such as

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);

    }

Is this approach correct, and if so, is it possible to return this as a dynamic type?

Answers were correct, was making this far too complex. Solution is now:

public dynamic GetProperty(string _propertyName)
{
    var currentVariables = m_context.Foo.OrderByDescending(g => g.FooId).FirstOrDefault();

    return currentVariables.GetType().GetProperty(_propertyName).GetValue(currentVariables, null);
}

回答1:


public static object ReflectPropertyValue(object source, string property)
{
     return source.GetType().GetProperty(property).GetValue(source, null);
}



回答2:


You're going way overboard with the samples you provide.

The method you're looking for:

public static object GetPropValue( object target, string propName )
 {
     return target.GetType().GetProperty( propName ).GetValue(target, null);
 }

But using "var" and "dynamic" and "Expression" and "Lambda"... you're bound to get lost in this code 6 months from now. Stick to simpler ways of writing it



来源:https://stackoverflow.com/questions/13766198/c-sharp-accessing-property-values-dynamically-by-property-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!