在通用方法c#

时间:2015-06-10 23:36:26

标签: c# deserialization generic-method

我需要在类中反序列化一个带有特殊编码的字符串,比如funcion" JsonConvert.DeserializeObject<>" NewtonSoft库,我写了这段代码:

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: 问题是这段代码不能正常工作,请问我的问题没有什么问题。用另一种语言很难解释,所以我写了一个示例代码,它应该会看到问题。

1 个答案:

答案 0 :(得分: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(); }。