C#通过属性名访问动态属性值 [英] C# accessing property values dynamically by property name

查看:112
本文介绍了C#通过属性名访问动态属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解决的问题是如何写这需要在属性名作为字符串的方法,并返回分配给所述属性的值。



我的模型类被声明类似于:

 公共类Foo 
{
公众诠释FooId
公众诠释参数1
公共双参数2
}

和从我的方法中我希望做一些类似的

  VAR财产=的getProperty(参数1)
VAR property2 =的getProperty(参数2)

我目前尝试使用表达式,如

 公共动态的getProperty(字符串_propertyName)
做到这一点{
变种currentVariables = m_context.Foo.OrderByDescending(X => x.FooId).FirstOrDefault();

变量参数= Expression.Parameter(typeof运算(富),富);
VAR财产= Expression.Property(参数,_propertyName);

变种的λ= Expression.Lambda< Func键< GlobalVariableSet,布尔>>(参数);

}

这是方法正确,如果是这样,是否有可能返回这是一个动态类型?



答案是正确的,是使这个过于复杂。解决方案现在是:



 公共动态的getProperty(字符串_propertyName)
{
VAR currentVariables = m_context.Foo .OrderByDescending(G => g.FooId).FirstOrDefault();

返回currentVariables.GetType()的getProperty(_propertyName).GetValue(currentVariables,NULL);
}


解决方案

 公共静态对象ReflectPropertyValue(对象源,字符串属性)
{
返回source.GetType()的getProperty(财产).GetValue(源,NULL);
}


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

解决方案

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

这篇关于C#通过属性名访问动态属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆