【问题标题】:Using Reflection in C# to Generate Entire Property Call from String在 C# 中使用反射从字符串生成整个属性调用
【发布时间】:2013-12-04 11:28:59
【问题描述】:

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

我需要做的是使用字符串生成整个调用。例如"Object1.Object2.Property"。

如何在 C# 中做到这一点?

如果我不能为此使用反射,我可以使用什么?

仅供参考,我在 ASP.NET 中使用它来使用绑定到模型中该属性的表单字段的名称来访问模型属性。如果有人知道另一种解决方法,请提出建议。

谢谢

【问题讨论】:

  • 在点上分割字符串,使用递归,但听起来你可以使用custom model binder
  • jheddings 回答此链接符合您的描述:stackoverflow.com/questions/1196991/…
  • @CodeCaster 我正在考虑这个问题。例如,这是否也适用于“Object.Property[1]”?
  • 如果您将[n] 解析为Property.GetValue()index 参数,就会出现这种情况。

标签: c# asp.net-mvc reflection


【解决方案1】:

包括这些命名空间:

using System.Reflection;
using System.Linq;

并尝试这样的事情:

public string ReadProperty(object object1)
{
    var object2Property = object1.GetType().GetProperties().FirstOrDefault(x => x.Name == "Object2");
    if (object2Property != null)
    {
        var anyProperty = object2Property.GetType().GetProperties().FirstOrDefault(x => x.Name == "Property");
        if (anyProperty != null)
        {
            var object2Value = object2Property.GetValue(object1, null);

            if (object2Value != null)
            {
                var valueProperty = anyProperty.GetValue(object2Value, null);

                return valueProperty;
            }
        }
    }

    return null;
}

只需将属性名称替换为正确的属性即可。

【讨论】:

    【解决方案2】:

    这是一个使用指定字符串获取属性值的工作代码:

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

    然后就可以获取值查询,包括数组,例如:

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

    【讨论】:

      猜你喜欢
      • 2010-11-14
      • 1970-01-01
      • 2020-08-01
      • 2016-06-16
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      相关资源
      最近更新 更多