-3

I need deserialize a string with a special encode in a class, like the funcion "JsonConvert.DeserializeObject<>" of NewtonSoft library, I wrote this code:

public void getMembersInfo()
{
    Dictionary<String, String> dict = new Dictionary<String, String>();
    dict.Add("name", "Name Test");
    dict.Add("address", "Addss Test");

    Members test = DeserializeObject<Members>(dict);
    Console.WriteLine("Var Name: " + test.name);
}


//Really "value" is a string type, but with "Dictionary" is more easy simulate the problem.
public static T DeserializeObject<T>(Dictionary<string, string> value)
{
    var type = typeof(T);
    var TheClass = (T)Activator.CreateInstance(type);
    foreach (var item in value)
    {
        type.GetProperty(item.key).SetValue(TheClass, item.value, null);
    }
    return (T)TheClass;
}


public class Members
{
    public String name;
    public Int age;
    public String address;
}

EDIT #1: The problem is that this code not work fine, do not what the problem with my question. It is difficult to explain in another language, so I wrote an example code, in it will should see the problem.

4

1 回答 1

0

如果您在问题中发布的代码实际上可以编译,那将非常有帮助。在发布之前,您似乎甚至没有花时间尝试您的代码。在编译器的帮助下,我发现你的代码应该是这样的:

public void getMembersInfo()
{
    Dictionary<String, String> dict = new Dictionary<string, string>();
    dict.Add("name", "Name Test");
    dict.Add("address", "Addss Test");

    Members test = DeserializeObject<Members>(dict);
    Console.WriteLine("Var Name: " + test.name);
}

//Really "value" is a string type, but with "Dictionary" is more easy simulate the problem.
public static T DeserializeObject<T>(Dictionary<string, string> value)
{
    var type = typeof(T);
    var TheClass = (T)Activator.CreateInstance(type);
    foreach (var item in value)
    {
        type.GetField(item.Key).SetValue(TheClass, item.Value);
    }
    return (T)TheClass;
}

public class Members
{
    public String name;
    public int age;
    public String address;
}

我想我可以说的唯一一个实际的逻辑错误是你.GetProperty(...)在应该使用.GetField(...).

否则,它会建议放弃(T)在线return (T)TheClass;,并且您应该where T : new对方法施加约束DeserializeObject<T>,然后简单地调用var TheClass = new T();.

于 2015-06-11T00:34:21.407 回答