Casting, reflection or?
I'm trying to write a simple lib for consuming a few JSON API endpoints and processing their contents with callbacks.
I'm trying to cast the "parsed" variable to its actual class (as it is known during runtime). Psuedo code as follows:
Is this just impossible or am I implenting this stuff wrong?
I'm trying to cast the "parsed" variable to its actual class (as it is known during runtime). Psuedo code as follows:
public interface IType
{
public string Type { get; set; }
}
public class TypeA : IType
{
public string Type { get; set; }
public string FancyA { get; set; }
}
public class TypeB : IType
{
public string Type { get; set; }
public string FancyB { get; set; }
}
void Get(json)
{
var x = GetJson;
IType returnObject = null;
switch(x.GetType)
{
"TypeA":
returnObject = JsonSerializer.Deserialize<TypeA>(x);
break;
"TypeB":
returnObject = JsonSerializer.Deserialize<TypeB>(x);
break;
}
return returnObject;
}
void DoParse()
{
var callbacks = Dictionary<string, Action<IType>> { ("TypeA", DoStuffTypeA) };
while(true)
{
var content = Retrieve();
var parsed = Get(content);
var callback = callbacks[parsed.Type]
callback.Invoke(parsed)
}
}
// Works
void DoStuffTypeA(IType content)
{
//...
}
// Doesn't work
void DoStuffTypeA(TypeA content)
{
//...
}public interface IType
{
public string Type { get; set; }
}
public class TypeA : IType
{
public string Type { get; set; }
public string FancyA { get; set; }
}
public class TypeB : IType
{
public string Type { get; set; }
public string FancyB { get; set; }
}
void Get(json)
{
var x = GetJson;
IType returnObject = null;
switch(x.GetType)
{
"TypeA":
returnObject = JsonSerializer.Deserialize<TypeA>(x);
break;
"TypeB":
returnObject = JsonSerializer.Deserialize<TypeB>(x);
break;
}
return returnObject;
}
void DoParse()
{
var callbacks = Dictionary<string, Action<IType>> { ("TypeA", DoStuffTypeA) };
while(true)
{
var content = Retrieve();
var parsed = Get(content);
var callback = callbacks[parsed.Type]
callback.Invoke(parsed)
}
}
// Works
void DoStuffTypeA(IType content)
{
//...
}
// Doesn't work
void DoStuffTypeA(TypeA content)
{
//...
}Is this just impossible or am I implenting this stuff wrong?