我有一个对象列表通过序列化来找我。 但我知道如下:
列表的所有类型都具有相同的类型。我只能动态地知道这种类型。例如:
list[0].GetType()
如何使用上述条件将所有列表转换为通用列表?
P.S。我反序列化了一个JSON的对象数组
{
"Message": [
{
"__type": "GameResponse:#Bridge3.Server",
"GameId": 1,
"GameName": "Game1 ",
"PlayerId": 1
},
{
"__type": "GameResponse:#Bridge3.Server",
"GameId": 2,
"GameName": "Game2 ",
"PlayerId": 1
}
}
答案 0 :(得分:2)
您可以使用dynamic
关键字:
interface ICar {}
interface IAnimal {}
class Program
{
static void Dispatch(dynamic list)
{
Console.WriteLine("Dispatch called");
DoSomething(list);
}
static void DoSomething<T>(List<T> genericList)
{
Console.WriteLine("Generic unconstrained method called");
}
static void DoSomething(List<IAnimal> animalList)
{
Console.WriteLine("Do something WILD");
}
static void DoSomething(List<ICar> carList)
{
Console.WriteLine("Calculate loans");
}
static void Main()
{
object deserializedList = new List<ICar>();
Dispatch(deserializedList);
}
}
答案 1 :(得分:1)
您可以使用反射创建强类型列表。您不会在代码中使用该类型,但列表类型将被修复。
//DetermineSerializedType here would be your own method to determine the type you have
Type deserializedType = DetermineSerializedType(serializedData);
Type genericType = typeof(List<>).MakeGenericType(deserializedType);
ConstructorInfo ctor = genericType.GetConstructor(new Type[] { });
object inst = ctor.Invoke(new object[] { });
IList list = inst as IList;
编辑我个人认为Grozz提供的动态解决方案更清晰。