在泛型方法中反序列化字符串#

Deserialize string in generic method c#

我需要在 class 中反序列化一个带有特殊编码的字符串,就像 NewtonSoft 库的函数 "JsonConvert.DeserializeObject<>" 一样,我写了这段代码:

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;
}

编辑#1: 问题是这段代码不能正常工作,我的问题没有什么问题。用另一种语言很难解释,所以我写了一个示例代码,在里面应该会看到问题。

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

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;
}

我认为我唯一可以说的是一个实际的逻辑错误,就是你在应该使用 .GetField(...) 的时候使用了 .GetProperty(...)

否则它会建议在 return (T)TheClass; 行上删除 (T) 并且你应该在 DeserializeObject<T> 方法上放置一个 where T : new 约束,然后简单地调用 var TheClass = new T();.