Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 试图将对象取消装箱到IEnumerable,get IEnumerable是一个';类型';但是像';变量';错误_C#_Casting_Ienumerable - Fatal编程技术网

C# 试图将对象取消装箱到IEnumerable,get 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

我想将一个对象解装箱到IEnumerable中。我检查对象是否可以指定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中的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。)