Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good day,

I need to make function that will iterate on Dictionary that stores variable name and variable`s new value. After that, I need to update class variable with that value.

C#
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);
    	}
    }


It works but I want little improvement and I absolutely don't know if it is possible.
As you can see, that function can accept any class, not just one specific.

If I have class like this

C#
class test
    {
    	public string age;
    }


And I would use function this way, it would work.

C#
UpdateValues(typeof(test), new Dictionary<string, string>{{"age", "17"}});


Problem is if I have class like this and I would like to update "subfield" (field in field)

C#
class test
    {
    	public string age;
    }
    
    class test2
    {
    	public test data;
    }


I was thinking that syntax could be something like this, but I have no idea how could I do it.

C#
UpdateValues(typeof(test2), new Dictionary<string, string>{{"data.age", "17"}});


To sum it up, I need to make function that will take class that is stored in another class. Function will iterate trough the dictionary and update fields of class and even her subfields.

What I have tried:

I've already made working function that can edit child variable of some object.
Posted
Comments
Tomas Takac 23-Dec-16 7:23am    
You are on the right track, the dot notation is a good idea. Now you just need to refactor UpdateValues a bit and call it recursively.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900