C#通过属性名动态访问属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13766198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:44:37  来源:igfitidea点击:

C# accessing property values dynamically by property name

c#dynamiclambda

提问by Thewads

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

采纳答案by Dzmitry Martavoi

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

回答by Sten Petrov

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

但是使用“var”和“dynamic”以及“Expression”和“Lambda”……你一定会在 6 个月后迷失在这段代码中。坚持更简单的写作方式