편집 :이 근처인가 너는 무엇을 요구하고 있는가?
코드 :
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;
}
}
}
결과 : 좋은 Minimal, Complete, and Verifiable code example없이
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
감사합니다. Eric. 나는 그것을 시도했지만 요소 유형을 갖게되면 그 유형의 목록에 캐스트 할 수 없습니다. 나는 이런 식으로 시도 : var myCastedList = (List) genericData; List에있는 ElementType이 맘에 들지 않았습니다. 변수로 사용하려고했으나 Type으로 사용하려고했습니다. –
rvb01
표현식을 사용할 수 있으며 제네릭 형식에 많은 융통성이 있습니다. 원하는 형식으로 캐스팅 할 형식을 식별하고 실행하면 Expression.Convert를 사용할 수 있습니다. https://msdn.microsoft.com/en-us/library/mt654265.aspx 자세한 예제를 작성하려고 할 수 있습니다. – Eric
당신이 얻고 자하는리스트의 대상의 유형을 알고 있습니까? – Eric