在C#中使用反射来生成字符串整个属性呼叫 [英] Using Reflection in C# to Generate Entire Property Call from String

查看:171
本文介绍了在C#中使用反射来生成字符串整个属性呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用C#反射找到使用对象的字符串(如Property1)的属性。

I know that I can use C# reflection to find a property using a string (e.g. "Property1") of an object.

我需要做的就是生成使用字符串整个呼叫什么。例如Object1.Object2.Property。

What I need to do is generate the entire call using a string. e.g. "Object1.Object2.Property".

我怎样才能做到这在C#?

How can I do this in C#?

如果我不能用这种反思,我能有什么用?

If I can't use reflection for this, what can I use?

仅供参考我使用这个在ASP.NET访问使用结合到模型中的该属性的表单字段的名称模型属性。如果有人知道解决这个另一种方式,请建议吧。

FYI I am using this in ASP.NET to access model properties using the name of the form field that binds to that property in the model. If anyone knows another way around this, please suggest it.

感谢

推荐答案

下面是一个工作code来获得属性值与指定的字符串:

Here is a working code to get property value with specified string:

static object GetPropertyValue(object obj, string propertyPath)
{
    System.Reflection.PropertyInfo result = null;
    string[] pathSteps = propertyPath.Split('/');
    object currentObj = obj;
    for (int i = 0; i < pathSteps.Length; ++i)
    {
        Type currentType = currentObj.GetType();
        string currentPathStep = pathSteps[i];
        var currentPathStepMatches = Regex.Match(currentPathStep, @"(\w+)(?:\[(\d+)\])?");
        result = currentType.GetProperty(currentPathStepMatches.Groups[1].Value);
        if (result.PropertyType.IsArray)
        {
            int index = int.Parse(currentPathStepMatches.Groups[2].Value);
            currentObj = (result.GetValue(currentObj) as Array).GetValue(index);
        }
        else
        {
            currentObj = result.GetValue(currentObj);
        }

    }
    return currentObj;
}

然后你就可以得到价值查询,包括阵列,例如:

And then you can get values queries, including arrays, for example:

var v = GetPropertyValue(someClass, "ArrayField1[5]/SomeField");

这篇关于在C#中使用反射来生成字符串整个属性呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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