-3

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: 問題は、このコードが正常に機能しないことです。私の質問に問題はありません。別の言語で説明するのは難しいので、サンプル コードを書きました。その中に問題が表示されるはずです。

4

1 に答える 1