简体   繁体   English

如何使用字符串属性路径获取/设置属性值?

[英]How to get/set value of properties using string property paths?

Let's say we have a class Root that has BasicDetails class property and then basicDetails has two properties.假设我们有一个 class 根,它具有 BasicDetails class 属性,然后 basicDetails 有两个属性。 A string "Name" and a dynamic object called "CustomAttributes".一个字符串“Name”和一个名为“CustomAttributes”的动态 object。

I want to get the value in the following manner:我想通过以下方式获取值:

  var root = new Root();
  root.BasicDetails.Name = "Samurai";
  root.BasicDetails.CustomAttributes.phone = "12345";
  string res1 = GetDeepPropertyValue(root, "BasicDetails.CustomAttributes.Phone").ToString();
  string res2 = GetDeepPropertyValue(root, "BasicDetails.Name").ToString();

The following is the code I have tried (based on another answer on SO):以下是我尝试过的代码(基于 SO 上的另一个答案):

public static object GetDeepPropertyValue(object src, string propName)
{
    if (propName.Contains('.'))
    {
        string[] Split = propName.Split('.');
        string RemainingProperty = propName.Substring(propName.IndexOf('.') + 1);
        return GetDeepPropertyValue(src.GetType().GetProperty(Split[0]).GetValue(src, null), RemainingProperty);
    }
    else
        return src.GetType().GetProperty(propName).GetValue(src, null);
}

The following are the classes:以下是课程:

public class Root
{
    public Root()
    {
        BasicDetails = new BasicDetails();
    }
    public BasicDetails BasicDetails { get;set;}
}
public class BasicDetails
{
    public BasicDetails()
    {
        CustomAttributes = new ExpandoObject();
    }
    public string Name { get; set; }
    public dynamic CustomAttributes { get; set; }
}

The function that I have tried is throwing null reference error.我试过的 function 抛出 null 参考错误。 Unfortunately I do not understand reflection too well so at the moment I am monkey patching.不幸的是,我不太了解反射,所以目前我正在修补猴子。 If someone could please explain c#how this can be done it would be great.如果有人可以请解释c#如何做到这一点,那就太好了。 Thank you in advance.先感谢您。

Following method gets values from nested properties:以下方法从嵌套属性中获取值:

    public static object GetPropertyValue(object src, string propName)
    {
        if (src == null) throw new ArgumentException("Value cannot be null.", "src");
        if (propName == null) throw new ArgumentException("Value cannot be null.", "propName");

        if (propName.Contains("."))//complex type nested
        {
            var temp = propName.Split(new char[] { '.' }, 2);
            return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
        }
        else
        {
            if (src is ExpandoObject)
            {
                var expando = src as IDictionary<string, object>;

                if (expando != null)
                {
                    object obj;
                    expando.TryGetValue(propName, out obj);
                    return obj;
                }

                return null;
            }
            else
            {
                var prop = src.GetType().GetProperty(propName);
                return prop != null ? prop.GetValue(src, null) : null;
            }
        }
    }

Usage:用法:

 string res1 = GetPropertyValue(root, "BasicDetails.CustomAttributes.phone") as string;
 string res2 = GetPropertyValue(root, "BasicDetails.Name") as string;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用字符串变量获取属性值? - How to get the Property value using string Variable? 如何通过属性名称字符串使用动态从Com互操作对象获取/设置值 - how to get/set value from Com interop object using dynamic by property name string 使用FakeItEasy,如何在假冒的属性上设置值? - Using FakeItEasy, how to get the value set on a property on a fake? 属性属性的反射设置值 - Reflection set value of a properties property 如果该对象是使用反射位于列表内的对象的属性,则如何设置该对象的属性及其值 - How to set Object's properties and its value if that Object is a property of Object that is inside of the List using Reflections 使用获取集访问器时访问属性的属性 - Accessing properties of a property while using get set accessors 如何根据字符串的值设置实例的属性? - how to set a property of an instance based on the value of a string? 如何根据其他 2 个属性的值设置 1 个属性的值? - How to set the value of 1 property depending on the values of 2 other properties? 如何获取无法使用C#中的AutomationElement属性访问的自定义属性值 - How to get a custom property value which cannot be accessed using AutomationElement properties in c# 使用反射从字符串中获取属性值 - Get property value from string using reflection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM