c#-通过字符串从局部变量获取属性

在方法内部,我进行了一些Web服务调用来获取数据,如下所示:

public void SomeMethod()
{
    var user = userWS.GetUsers();
    var documents = documentWS.GetDocuments();
}

我也有一个XML文件,用户可以在其中告诉要映射的属性. XML看起来像这样:

<root>
  <item id="username" mapper="user.username.value" />
  <item id="document1" mapper="documents.document1.value" />
</root>

所以我基本上想要做的是执行映射器属性内的字符串.这样我有这样的事情:

public void SomeMethod()
{
    var user = userWS.GetUsers();
    var documents = documentWS.GetDocuments();

    // returns: "user.username.value"
    string usernameProperty = GetMapperValueById ( "username" );

    var value = Invoke(usernameProperty);
}

所以它应该像我在调用var value = user.username.value;一样.手动在我的代码中.

但是,如何从字符串调用此操作?

解决方法:

通常,您无法在运行时获取局部变量的值(有关参考,请参见this question),但是基于我自己的answer from another question,您可以使用GetPropertyValue方法来解决此问题,以创建具有所需属性的局部对象:

public void SomeMethod()
{
    var container = new 
    {
        user = userWS.GetUsers(),
        documents = documentWS.GetDocuments()
    }

    // returns: "user.username.value"
    string usernameProperty = GetMapperValueById ( "username" );

    var value = GetPropertyValue(container, usernameProperty);
}

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;
}
上一篇:java.sql.SQLException: The user specified as a definer ('userxxx'@'%') does not


下一篇:java中静态代理模式与动态代理模式