C# 如何确定零长度集合的元素是什么类型?
我正在编写一个通用的保存对象图方法 如果我的对象图包含一个集合,则该集合的所有元素都可能已被删除 为了持久保存删除,我需要知道集合将包含什么类型的实体C# 如何确定零长度集合的元素是什么类型?,c#,entity-framework,C#,Entity Framework,我正在编写一个通用的保存对象图方法 如果我的对象图包含一个集合,则该集合的所有元素都可能已被删除 为了持久保存删除,我需要知道集合将包含什么类型的实体 navProps = GetNavigationProperties(originalEntity); foreach (PropertyInfo navProp in navProps) { Type propertyType = navProp.PropertyType; bool isCollection = prope
navProps = GetNavigationProperties(originalEntity);
foreach (PropertyInfo navProp in navProps)
{
Type propertyType = navProp.PropertyType;
bool isCollection = propertyType.GetInterfaces().Any(x => x == typeof(IEnumerable)) &&
!(propertyType == typeof(string));
object obj = navProp.GetValue(item);
if (isCollection)
{
// I need to know what type the elements in the collection so I can retrieve the ones that might need deleting.
}
}
您有两种情况:要么它只是
IEnumerable
,那么您只能知道元素的类型是object
。这就是您的代码当前所做的
第二种可能是您有一个强类型的IEnumerable
,在这种情况下,您可以执行以下操作:
var enumerableTInterface = propertyType
.GetInterfaces()
.FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition()
== typeof(IEnumerable<>));
bool isStronglyTypedCollection = enumerableTInterface != null;
if (isStronglyTypedCollection)
{
var elementType = enumerableTInterface.GetGenericArguments()[0];
//...
var enumerableinterface=propertyType
.GetInterfaces()
.FirstOrDefault(x=>x.IsGenericType&&x.GetGenericTypeDefinition()
==类型(IEnumerable));
bool isStronglyTypedCollection=EnumerableInterface!=无效的
if(isStronglyTypedCollection)
{
var elementType=EnumerableInterface.GetGenericArguments()[0];
//...
告诉我们原始定义可能是什么样子,例如IList等。