I have a (sql) table with these entries:
Table:
Type (varchar) Json (varchar)
MyClassA { "Id": 1, "Name": "OneName" }
MyClassB { "Id": 2, "Name": "TwoName" }
I need to call a method in ClassA and/or ClassB to change the Name property.
Something like the next code:
public void Test(string type, string json)
{
Type type = Type.GetType($"MyNamespace.a.b.{type}, MyDll");
// Some code here....
// - Casting to IData ??
// - var obj = JsonConvert.DeserializeObject(json); ??
// - var obj = JsonConectt.DeserializeObject<type>(json) ??
// - var x = Convert.Change(...) ??
instance.DoSomething("bazinga");
}
public interface IData
{
void DoSomething();
}
public class MyClassA : IData
{
public int Id {get; set;}
public string Name {get; set;}
public void DoSomething(string newName)
{
Name = newName;
}
}
public class MyClassB : IData
{
public int Id {get; set;}
public string Name {get; set;}
public void DoSomething(string newName)
{
name = $"{Id}, {newName}";
}
}
Attempt A:
var obj = JsonConvert.DeserializeObject(json);
var ins = obj as IData;
// ins = null
Attempt B:
dynamic obj = JsonConvert.DeserializeObject<dynamic>(json);
// failed
Attempt C:
var obj = JsonConvert.DeseriallizeObject<type>(json);
// Not allowed to use 'type' in this way.
Aucun commentaire:
Enregistrer un commentaire