public bool IsList(object value)
{
Type type = value.GetType();
// Check if type is a generic list of any type
}
Який найкращий спосіб перевірити, чи є даний об’єкт списком, чи його можна передати до списку?
public bool IsList(object value)
{
Type type = value.GetType();
// Check if type is a generic list of any type
}
Який найкращий спосіб перевірити, чи є даний об’єкт списком, чи його можна передати до списку?
Відповіді:
using System.Collections;
if(value is IList && value.GetType().IsGenericType) {
}
List<T>і ObservableCollection<T>реалізації IList.
Для вас, хлопці, яким подобається використовувати методи розширення:
public static bool IsGenericList(this object o)
{
var oType = o.GetType();
return (oType.IsGenericType && (oType.GetGenericTypeDefinition() == typeof(List<>)));
}
Отже, ми могли б зробити:
if(o.IsGenericList())
{
//...
}
return oType.GetTypeInfo().IsGenericType && oType.GetGenericTypeDefinition() == typeof(List<>);
IList<>натомість безпечнішою?
bool isList = o.GetType().IsGenericType
&& o.GetType().GetGenericTypeDefinition() == typeof(IList<>));
Спираючись на відповідь Віктора Родрігеса, ми можемо розробити інший метод дженериків. Насправді оригінальне рішення можна звести лише до двох рядків:
public static bool IsGenericList(this object Value)
{
var t = Value.GetType();
return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>);
}
public static bool IsGenericList<T>(this object Value)
{
var t = Value.GetType();
return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<T>);
}
Ось реалізація, яка працює в .NET Standard і працює проти інтерфейсів:
public static bool ImplementsGenericInterface(this Type type, Type interfaceType)
{
return type
.GetTypeInfo()
.ImplementedInterfaces
.Any(x => x.GetTypeInfo().IsGenericType && x.GetGenericTypeDefinition() == interfaceType);
}
І ось тести (xunit):
[Fact]
public void ImplementsGenericInterface_List_IsValidInterfaceTypes()
{
var list = new List<string>();
Assert.True(list.GetType().ImplementsGenericInterface(typeof(IList<>)));
Assert.True(list.GetType().ImplementsGenericInterface(typeof(IEnumerable<>)));
Assert.True(list.GetType().ImplementsGenericInterface(typeof(IReadOnlyList<>)));
}
[Fact]
public void ImplementsGenericInterface_List_IsNotInvalidInterfaceTypes()
{
var list = new List<string>();
Assert.False(list.GetType().ImplementsGenericInterface(typeof(string)));
Assert.False(list.GetType().ImplementsGenericInterface(typeof(IDictionary<,>)));
Assert.False(list.GetType().ImplementsGenericInterface(typeof(IComparable<>)));
Assert.False(list.GetType().ImplementsGenericInterface(typeof(DateTime)));
}
Я використовую такий код:
public bool IsList(Type type) => IsGeneric(type) && (
(type.GetGenericTypeDefinition() == typeof(List<>))
|| (type.GetGenericTypeDefinition() == typeof(IList<>))
);
Напевно, найкращим способом було б зробити щось подібне:
IList list = value as IList;
if (list != null)
{
// use list in here
}
Це дасть вам максимальну гнучкість, а також дозволить працювати з багатьма різними типами, що реалізують IListінтерфейс.