Yazıyı derinlemesine düşünerek Telde etmenin bir yolu var IEnumerable<T>mı?
Örneğin
değişken bir bilgim var IEnumerable<Child>; Düşünme yoluyla Çocuğun türünü geri almak istiyorum
Yazıyı derinlemesine düşünerek Telde etmenin bir yolu var IEnumerable<T>mı?
Örneğin
değişken bir bilgim var IEnumerable<Child>; Düşünme yoluyla Çocuğun türünü geri almak istiyorum
Yanıtlar:
IEnumerable<T> myEnumerable;
Type type = myEnumerable.GetType().GetGenericArguments()[0];
Böylece,
IEnumerable<string> strings = new List<string>();
Console.WriteLine(strings.GetType().GetGenericArguments()[0]);
baskılar System.String.
Şunun için MSDN'ye bakınType.GetGenericArguments .
Düzenleme: Bunun yorumlardaki endişeleri gidereceğine inanıyorum:
// 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]);
}
Bazı nesneler birden fazla jenerik uygular IEnumerable, bu nedenle bunların bir numaralandırmasını döndürmek gerekir.
Düzenleme: Yine de söylemeliyim ki, bir sınıfın IEnumerable<T>birden fazlası için uygulaması korkunç bir fikir T.
Ben sadece bir uzatma yöntemi yapardım. Bu, ona attığım her şeyle çalıştı.
public static Type GetItemType<T>(this IEnumerable<T> enumerable)
{
return typeof(T);
}
Benzer bir problemim vardı. Seçilen cevap, gerçek durumlar için işe yarar. Benim durumumda sadece bir tipim vardı (birPropertyInfo ).
Tipin kendisi typeof(IEnumerable<T>)bir uygulaması olmadığında seçilen cevap başarısız olurIEnumerable<T> .
Bu durum için aşağıdakiler çalışır:
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;
}
Type.GenericTypeArguments- yalnızca dotNet FrameWork sürümü> = 4.5 için. Aksi takdirde - Type.GetGenericArgumentsonun yerine kullanın.
IEnumerable<T>(Jenerikler yoluyla) biliyorsanız , o zaman typeof(T)çalışmalısınız. Aksi takdirde (için objectveya genel olmayan IEnumerable), uygulanan arayüzleri kontrol edin:
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);
Type typeparametre yerine bir parametreyle kullanmaya çalışan herkes için küçük bir aldatma object obj: obj.GetType()ile değiştiremezsiniz , typeçünkü typeof(IEnumerable<T>)iletirseniz hiçbir şey alamazsınız. Bunu typeaşmak için, genel olup olmadığını görmek için kendini IEnumerable<>ve sonra arayüzlerini test edin .
Tartışma için çok teşekkür ederim. Aşağıdaki çözümün temeli olarak kullandım, bu beni ilgilendiren tüm durumlar için iyi çalışıyor (IEnumerable, türetilmiş sınıflar, vb.). Ayrıca birinin ihtiyacı olursa burada paylaşmam gerektiğini düşündüm:
Type GetItemType(object someCollection)
{
var type = someCollection.GetType();
var ienum = type.GetInterface(typeof(IEnumerable<>).Name);
return ienum != null
? ienum.GetGenericArguments()[0]
: null;
}
someCollection.GetType().GetInterface(typeof(IEnumerable<>).Name)?.GetGenericArguments()?.FirstOrDefault()
Ya bir IEnumerable<T>ya da T- GenericTypeArgumentsyerine kullanılacağı daha basit durumlar için bir alternatif GetGenericArguments().
Type inputType = o.GetType();
Type genericType;
if ((inputType.Name.StartsWith("IEnumerable"))
&& ((genericType = inputType.GenericTypeArguments.FirstOrDefault()) != null)) {
return genericType;
} else {
return inputType;
}
Bu, Eli Algranti'nin çözümünde bir gelişmedir çünkü aynı zamanda IEnumerable<> türün miras ağacında herhangi bir düzeyde .
Bu çözüm, eleman türünü herhangi birinden alacaktır Type. Tür bir değilse IEnumerable<>, aktarılan türü döndürür. Nesneler için kullanın GetType. Türler için kullanın typeof, ardından sonuçta bu uzantı yöntemini çağırın.
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;
}
}
Bunun biraz eski olduğunu biliyorum, ancak bu yöntemin yorumlarda belirtilen tüm sorunları ve zorlukları kapsayacağına inanıyorum. İşime ilham verdiği için Eli Algranti'ye teşekkür ederim.
/// <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<>);
}
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();
}
Bu özyinelemeli bir işlevdir ve iç genel tür içermeyen somut bir tür tanımı elde edene kadar genel türler listesinin derinliklerine iner.
Bu yöntemi şu türle test ettim:
ICollection<IEnumerable<ICollection<ICollection<IEnumerable<IList<ICollection<IEnumerable<IActionResult>>>>>>>>
hangisi geri dönmeli IActionResult
typeof(IEnumerable<Foo>). ilk genel bağımsız değişkeni döndürür - bu durumda .GetGenericArguments()[0]typeof(Foo)
İşte okunamayan Linq sorgu ifade sürümüm ..
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);
}
Yöntemin jenerik olmayanları da IEnumerablehesaba kattığına dikkat edin object, bu durumda geri döner , çünkü Typeargüman olarak somut değil de bir örnek alır . Bu arada, x bilinmeyeni temsil ettiği için , alakasız olmasına rağmen bu videoyu ilginç buldum .