无法获取对象的泛型类型T.

时间:2017-03-10 22:28:23

标签: c# generics

我将对象传递给泛型方法,称为fromProperty和toProperty。对象是泛型类型的列表,但是当我尝试获取泛型类型时,我得到了一个' System.IndexOutOfRangeException'例外。这与方法本身是通用的有关,但它需要保持这种方式。

    private static Dictionary<string, List<object>> GetListAttributeDifferences<TFrom, TTo>(TFrom fromProperty, TTo toProperty)
        where TFrom : class
        where TTo : class
    {
        //Get types for list containing types
        Type fromPropertyListContainingType = fromProperty.GetType().GenericTypeArguments[0];
        Type toPropertyListContainingType = toProperty.GetType().GenericTypeArguments[0]; return null;}

此方法以这种方式调用

        public static Dictionary<string, List<object>> GetAttributeDifferences<TFrom, TTo>(TFrom fromObject, TTo toObject)
                where TFrom : class
                where TTo : class

            if (fromObject is IList && toObject is IList)
            {
                Dictionary<string, List<object>> listAttributeDifferences = GetListAttributeDifferences(fromObject, toObject);
            }}

1 个答案:

答案 0 :(得分:0)

使用GetGenericArgumentsSystem.Type方法

private static Dictionary<string, List<object>> GetListAttributeDifferences<TFrom, TTo>(TFrom fromProperty, TTo toProperty)
        where TFrom : class
        where TTo : class
{
    //Get types for list containing types
    Type fromPropertyListContainingType = fromProperty.GetType().GetGenericArguments()[0];
    Type toPropertyListContainingType = toProperty.GetType().GetGenericArguments()[0];
    return null;
}