如何动态地为嵌套对象赋值?

时间:2016-12-06 06:07:04

标签: c# .net dynamic-programming

我正在开展一个项目,我需要能够做到以下几点:

说,我们有Aa类是配置类:

public class Aa
{
    public Bb BbName { set; get; }
    public string Dd { set; get; }
}


public class Bb
{
    public string bb { set; get; }
    public string cc { set; get; }
}

我想从环境中获取变量,以便将它们分配给相应的属性。这就是我的意思:作为Environment.GetEnvironmentVariable的模拟,让我们使用Dictionary<string, string>。 安装程序将如下所示:

var dic = new Dictionary<string, string>();
dic.Add("Dd", "236.154");
dic.Add("BbName.bb", "value_for_Bb.bb"); // as you can see, I'm using nested object's full
dic.Add("BbName.cc", "value_for_Bb.cc"); // path, in order to be able to identify it

然后我写了一个方法,看起来像这样:

private static void ReadPropertiesRecursive<T>(T obj, Type type, List<string> prefixes)
{

    foreach (PropertyInfo property in type.GetProperties())
    {
        if (property.PropertyType.GetTypeInfo().IsClass && property.PropertyType != typeof(string))
        {
            prefixes.Add(property.Name);
            ReadPropertiesRecursive(obj, property.PropertyType, prefixes);
            prefixes.Remove(property.Name);
        }
        else
        {
            var propertyFullName = prefixes != null && prefixes.Count > 0 ? $"{prefixes.Aggregate((i, j) => i + "." + j)}.{property.Name}" : property.Name;

            property.SetValue(obj, dic[propertyFullName]);

            Console.WriteLine(propertyFullName); // just for debugging
        }
    }
}

因此,使用递归,我能够到达给定Type的所有嵌套对象,唯一剩下的就是为它们分配相应的值。我试图在property.SetValue(obj, dic[propertyFullName]);上执行此操作,但它会抛出错误,这是有道理的:obj是一个“根”对象,而不是我想直接赋值的对象。所以,我可能需要传递obj,而不是property的实例,这是obj的属性。那是对的吗?那会有用吗?如果是的话,我应该怎么做?

1 个答案:

答案 0 :(得分:0)

这就是诀窍:

Sub FilterResults()
    Dim res As Variant

    With ActiveSheet.Rows(1)
        res = Application.Match("Errors", .Cells, 0)
        If Not IsError(res) Then
            .AutoFilter Field:=res, Criteria1:="*-SERVICE CODE*"
            If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then '<--| if any cell filtered other than header (which is in row 3)
               MsgBox "Data"
               With .SpecialCells(xlCellTypeVisible)
                   ' code
               End With
            Else
               MsgBox "No Data"
            End If
        End If
    End With
End Sub