编辑:这是接近你在问什么?
代码:
void Main()
{
List<string> stringlist = new List<string> { "a", "b", "c" };
List<int> intlist = new List<int> { 1, 2, 3 };
string notList = "";
var expression = Expression.Call(typeof(Methods), "CastToList", new Type[] { stringlist.GetType(), stringlist.GetType().GetGenericArguments()[0] }, Expression.Constant(stringlist));
Expression.Lambda<Func<bool>>(expression).Compile()();
expression = Expression.Call(typeof(Methods), "CastToList", new Type[] { intlist.GetType(), intlist.GetType().GetGenericArguments()[0] }, Expression.Constant(intlist));
Expression.Lambda<Func<bool>>(expression).Compile()();
expression = Expression.Call(typeof(Methods), "CastToList", new Type[] { notList.GetType(), typeof(object) }, Expression.Constant(notList));
Expression.Lambda<Func<bool>>(expression).Compile()();
}
public static class Methods
{
public static void MapListToField<T>(List<T> genericList)
{
foreach (var element in genericList)
{
Console.Write("{0}, ", element.ToString());
}
Console.Write("\n");
}
public static bool CastToList<L, T>(L obj)
{
if (obj.GetType() == typeof(List<T>))
{
Console.Write("List contains objects of Type: {0}\n", typeof(T).ToString());
List<T> genericList = obj as List<T>;
MapListToField(genericList);
return true;
}
else
{
Console.Write("Not list, Type is: {0}\n", typeof(L).ToString());
return false;
}
}
}
结果:
List contains objects of Type: System.String
a, b, c,
List contains objects of Type: System.Int32
1, 2, 3,
Not list, Type is: System.String
谢谢埃里克。我尝试过,但一旦我有元素类型,我无法转换为该类型的列表。我尝试了这样的事情:var myCastedList =(List)genericData;它不喜欢我放在List中的ElementType,抱怨它是可变的,我试图用作类型 –
rvb01
您可以使用表达式,它们对泛型类型有很大的灵活性。一旦确定了要转换为所需类型和执行的类型,就可以使用Expression.Convert。 https://msdn.microsoft.com/en-us/library/mt654265.aspx 我可以尝试写一个详细的例子。 – Eric
你知道你期望得到的列表中的对象的类型吗? – Eric