C# 试图将对象取消装箱到IEnumerable,get IEnumerable是一个';类型';但是像';变量';错误
我想将一个对象解装箱到IEnumerable中。我检查对象是否可以指定IEnumerable,如果可以,我希望循环对象中的值。但是,当我执行以下操作时:C# 试图将对象取消装箱到IEnumerable,get IEnumerable是一个';类型';但是像';变量';错误,c#,casting,ienumerable,C#,Casting,Ienumerable,我想将一个对象解装箱到IEnumerable中。我检查对象是否可以指定IEnumerable,如果可以,我希望循环对象中的值。但是,当我执行以下操作时: if (typeof(IEnumerable<IRecord>).IsAssignableFrom(propertyValue.GetType())) { foreach (var property in IEnumerable<IRecord>(propertyValue)) { var
if (typeof(IEnumerable<IRecord>).IsAssignableFrom(propertyValue.GetType()))
{
foreach (var property in IEnumerable<IRecord>(propertyValue))
{
var test = property;
}
}
if(typeof(IEnumerable).IsAssignableFrom(propertyValue.GetType())
{
foreach(IEnumerable中的var属性(propertyValue))
{
var测试=属性;
}
}
IEnumerable给出了以下错误:
Error 1 'System.Collections.Generic.IEnumerable<test.Database.IRecord>' is a 'type' but is used like a 'variable' D:\test.Test\ElectronicSignatureRepositoryTest.cs 397 46 test.Test
错误1“System.Collections.Generic.IEnumerable”是一个“类型”,但与“变量”D:\test.test\ElectronicSignatureRepositoryTest.cs 397 46 test.test一样使用
如何将propertyValue指定为IEnumerable?您需要:
if (typeof(IEnumerable<IRecord>).IsAssignableFrom(propertyValue.GetType()))
{
foreach (var property in (IEnumerable<IRecord>)propertyValue)
{
var test = property;
}
}
if(typeof(IEnumerable).IsAssignableFrom(propertyValue.GetType())
{
foreach(在(IEnumerable)propertyValue中的var属性)
{
var测试=属性;
}
}
您还可以执行以下操作:
var enumerable = propertyValue as IEnumerable<IRecord>;
if (enumerable != null)
{
foreach (var property in enumerable)
{
var test = property;
}
}
var enumerable=属性值为IEnumerable;
if(可枚举!=null)
{
foreach(枚举中的var属性)
{
var测试=属性;
}
}
后者通常优于反射。(@Niek,而不是@mdm。)