program tip

IEnumerable에서 유형 T 가져 오기

radiobox 2020. 8. 23. 08:54
반응형

IEnumerable에서 유형 T 가져 오기


리플렉션 TIEnumerable<T>통해 유형을 검색하는 방법이 있습니까?

예 :

변수 IEnumerable<Child>정보가 있습니다. 반성을 통해 아이의 타입을 되찾고 싶어


IEnumerable<T> myEnumerable;
Type type = myEnumerable.GetType().GetGenericArguments()[0]; 

따라서

IEnumerable<string> strings = new List<string>();
Console.WriteLine(strings.GetType().GetGenericArguments()[0]);

인쇄합니다 System.String.

.NETMSDN참조하십시오 Type.GetGenericArguments.

편집 : 이것이 의견의 우려를 해결할 것이라고 믿습니다.

// returns an enumeration of T where o : IEnumerable<T>
public IEnumerable<Type> GetGenericIEnumerables(object o) {
    return o.GetType()
            .GetInterfaces()
            .Where(t => t.IsGenericType
                && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            .Select(t => t.GetGenericArguments()[0]);
}

일부 객체는 둘 이상의 제네릭을 구현 IEnumerable하므로 열거를 반환해야합니다.

편집 : 비록, 나는 IEnumerable<T>하나 이상의 클래스를 구현하는 것은 끔찍한 아이디어입니다 T.


나는 확장 방법을 만들 것입니다. 이것은 내가 던진 모든 것과 함께 작동했습니다.

public static Type GetItemType<T>(this IEnumerable<T> enumerable)
{
    return typeof(T);
}

비슷한 문제가있었습니다. 선택한 답변은 실제 인스턴스에 적용됩니다. 제 경우에는 (에서 PropertyInfo) 유형 만있었습니다 .

유형 자체가 typeof(IEnumerable<T>)의 구현 아닌 경우 선택한 답변이 실패합니다 IEnumerable<T>.

이 경우 다음이 작동합니다.

public static Type GetAnyElementType(Type type)
{
   // Type is Array
   // short-circuit if you expect lots of arrays 
   if (type.IsArray)
      return type.GetElementType();

   // type is IEnumerable<T>;
   if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (IEnumerable<>))
      return type.GetGenericArguments()[0];

   // type implements/extends IEnumerable<T>;
   var enumType = type.GetInterfaces()
                           .Where(t => t.IsGenericType && 
                                  t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                           .Select(t => t.GenericTypeArguments[0]).FirstOrDefault();
   return enumType ?? type;
}

IEnumerable<T>(제네릭을 통해) 알고 있으면 typeof(T)작동합니다. 그렇지 않으면 ( object또는 비 제네릭 IEnumerable) 구현 된 인터페이스를 확인하십시오.

        object obj = new string[] { "abc", "def" };
        Type type = null;
        foreach (Type iType in obj.GetType().GetInterfaces())
        {
            if (iType.IsGenericType && iType.GetGenericTypeDefinition()
                == typeof(IEnumerable<>))
            {
                type = iType.GetGenericArguments()[0];
                break;
            }
        }
        if (type != null) Console.WriteLine(type);

토론 해 주셔서 대단히 감사합니다. 나는 그것을 아래 솔루션의 기초로 사용했는데, 이는 나에게 관심이있는 모든 경우 (IEnumerable, 파생 클래스 등)에서 잘 작동합니다. 누군가가 필요로 할 경우를 대비하여 여기에 공유해야한다고 생각했습니다.

  Type GetItemType(object someCollection)
  {
    var type = someCollection.GetType();
    var ienum = type.GetInterface(typeof(IEnumerable<>).Name);
    return ienum != null
      ? ienum.GetGenericArguments()[0]
      : null;
  }

그냥 사용 typeof(T)

편집 : 또는 T가없는 경우 인스턴스화 된 개체에 .GetType (). GetGenericParameter ()를 사용합니다.


An alternative for simpler situations where it's either going to be an IEnumerable<T> or T - note use of GenericTypeArguments instead of GetGenericArguments().

Type inputType = o.GetType();
Type genericType;
if ((inputType.Name.StartsWith("IEnumerable"))
    && ((genericType = inputType.GenericTypeArguments.FirstOrDefault()) != null)) {

    return genericType;
} else {
    return inputType;
}

This is an improvement on Eli Algranti's solution in that it will also work where the IEnumerable<> type is at any level in the inheritance tree.

This solution will obtain the element type from any Type. If the type is not an IEnumerable<>, it will return the type passed in. For objects, use GetType. For types, use typeof, then call this extension method on the result.

public static Type GetGenericElementType(this Type type)
{
    // Short-circuit for Array types
    if (typeof(Array).IsAssignableFrom(type))
    {
        return type.GetElementType();
    }

    while (true)
    {
        // Type is IEnumerable<T>
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        {
            return type.GetGenericArguments().First();
        }

        // Type implements/extends IEnumerable<T>
        Type elementType = (from subType in type.GetInterfaces()
            let retType = subType.GetGenericElementType()
            where retType != subType
            select retType).FirstOrDefault();

        if (elementType != null)
        {
            return elementType;
        }

        if (type.BaseType == null)
        {
            return type;
        }

        type = type.BaseType;
    }
}

I know this is a bit old, but I believe this method will cover all the problems and challenges stated in the comments. Credit to Eli Algranti for inspiring my work.

/// <summary>Finds the type of the element of a type. Returns null if this type does not enumerate.</summary>
/// <param name="type">The type to check.</param>
/// <returns>The element type, if found; otherwise, <see langword="null"/>.</returns>
public static Type FindElementType(this Type type)
{
   if (type.IsArray)
      return type.GetElementType();

   // type is IEnumerable<T>;
   if (ImplIEnumT(type))
      return type.GetGenericArguments().First();

   // type implements/extends IEnumerable<T>;
   var enumType = type.GetInterfaces().Where(ImplIEnumT).Select(t => t.GetGenericArguments().First()).FirstOrDefault();
   if (enumType != null)
      return enumType;

   // type is IEnumerable
   if (IsIEnum(type) || type.GetInterfaces().Any(IsIEnum))
      return typeof(object);

   return null;

   bool IsIEnum(Type t) => t == typeof(System.Collections.IEnumerable);
   bool ImplIEnumT(Type t) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}

typeof(IEnumerable<Foo>).GetGenericArguments()[0] will return the first generic argument - in this case typeof(Foo).


this is how I usually do it (via extension method):

public static Type GetIEnumerableUnderlyingType<T>(this T iEnumerable)
    {
        return typeof(T).GetTypeInfo().GetGenericArguments()[(typeof(T)).GetTypeInfo().GetGenericArguments().Length - 1];
    }

Here's my unreadable Linq query expression version ..

public static Type GetEnumerableType(this Type t) {
    return !typeof(IEnumerable).IsAssignableFrom(t) ? null : (
    from it in (new[] { t }).Concat(t.GetInterfaces())
    where it.IsGenericType
    where typeof(IEnumerable<>)==it.GetGenericTypeDefinition()
    from x in it.GetGenericArguments() // x represents the unknown
    let b = it.IsConstructedGenericType // b stand for boolean
    select b ? x : x.BaseType).FirstOrDefault()??typeof(object);
}

Note the method also takes non-generic IEnumerable into account, it returns object in this case, because it takes a Type rather than a concrete instance as the argument. By the way, for x represents the unknown, I found this video insteresting, though it is irrelevant ..


public static Type GetInnerGenericType(this Type type)
{
  // Attempt to get the inner generic type
  Type innerType = type.GetGenericArguments().FirstOrDefault();

  // Recursively call this function until no inner type is found
  return innerType is null ? type : innerType.GetInnerGenericType();
}

This is a recursive function that will go depth first down the list of generic types until it gets a concrete type definition with no inner generic types.

I tested this method with this type: ICollection<IEnumerable<ICollection<ICollection<IEnumerable<IList<ICollection<IEnumerable<IActionResult>>>>>>>>

which should return IActionResult

참고URL : https://stackoverflow.com/questions/906499/getting-type-t-from-ienumerablet

반응형