简体   繁体   中英

Using Reflection in C# to Generate Entire Property Call from String

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

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

How can I do this in C#?

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

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.

Thanks

Include theses namespaces:

using System.Reflection;
using System.Linq;

and try something like this:

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

Just replace the names of properties for your correct proeprties.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM