FieldInfo更新字段的子字段

Mrg*_*ito 6 .net c# reflection system.reflection

美好的一天,

我需要创建将在存储变量名和变量的新值的Dictionary上迭代的函数.之后,我需要用该值更新类变量.

void UpdateValues(Type type, Dictionary<string, string> values)
{
    foreach (var value in values)
    {
        var fieldInfo = selected.GetComponent(type).GetType().GetField(value.Key);
        if (fieldInfo == null) continue;

        fieldInfo.SetValue(selected.GetComponent(type), value.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

它有效,但我想要一点改进,我绝对不知道是否可能.如您所见,该函数可以接受任何类,而不仅仅是一个类.

如果我有这样的课

class test
{
    public string age;
}
Run Code Online (Sandbox Code Playgroud)

我会以这种方式使用函数,它会工作.

UpdateValues(typeof(test), new Dictionary<string, string>{{"age", "17"}});
Run Code Online (Sandbox Code Playgroud)

问题是,如果我有这样的类,我想更新"子字段"(字段中的字段)

class test
{
    public string age;
}

class test2
{
    public test data;
}
Run Code Online (Sandbox Code Playgroud)

我认为语法可能是这样的,但我不知道我怎么能这样做.

UpdateValues(typeof(test2), new Dictionary<string, string>{{"data.age", "17"}});
Run Code Online (Sandbox Code Playgroud)

总结一下,我需要创建一个函数来获取存储在另一个类中的类.函数将通过字典迭代并更新类甚至是子字段的字段.

Mak*_*kin 1

我建议向您的方法添加递归调用以设置属性。我稍微改变了你的方法,因为我没有selected对象,它需要一个对象作为参数

void UpdateValues<T>(T obj,  Dictionary<string, string> values)
{
    foreach (var value in values)
    {       
        SetProperty(obj, value.Key, value.Value);
    }
}


public void SetProperty<T>( T obj, string valueKey, string value, Type type= null)
{
    var typeToUse = type ?? typeof(T);
    var pointIndex = valueKey.IndexOf(".");
    if (pointIndex!=-1)
    {
        var subKey = valueKey.Substring(0, pointIndex);
        var fieldInfo = typeToUse.GetField(subKey);
        var propObj =  fieldInfo.GetValue(obj)
                        ?? Activator.CreateInstance(fieldInfo.FieldType);           
        SetProperty(propObj, valueKey.Substring(pointIndex+1), value, fieldInfo.FieldType);
        fieldInfo.SetValue(obj, propObj);
    }
    else
    {       
        var fieldInfo = typeToUse.GetField(valueKey);       
        if (fieldInfo != null)
            fieldInfo.SetValue(obj, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

即使你定义它也有效

class test3
{
    public test2 data;
}
Run Code Online (Sandbox Code Playgroud)

并打电话

UpdateValues(t, new Dictionary<string, string>{{"age", "17"}}); 
UpdateValues(t2, new Dictionary<string, string> { { "data.age", "17" } });
UpdateValues(t3, new Dictionary<string, string> { { "data.data.age", "17" } });
Run Code Online (Sandbox Code Playgroud)

方法的第三个参数SetProperty不太好,我会避免它,但我不知道如何用泛型解决它,在创建后Activator得到object类型,并且对象没有字段age

您使用的 Dictionary<string, string>参数仅允许您设置字符串字段,因此您必须假设您没有任何其他字段。实际上,即使您使用 Dictionary<string, object>我建议这样做,这也会起作用。