2012-04-02 65 views
2

我想解除一个对象到IEnumerable。我检查是否可以为该对象分配一个IEnumerable,然后如果是这样,我想循环访问该对象中的值。然而,当我做到以下几点:尝试解除对IEnumerable的对象,得到IEnumerable是一个'类型',但用于'变量'错误

if (typeof(IEnumerable<IRecord>).IsAssignableFrom(propertyValue.GetType())) 
{ 
    foreach (var property in IEnumerable<IRecord>(propertyValue)) 
    { 
     var test = property; 
    } 
} 

了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 

我怎么能分配到的PropertyValue是一个IEnumerable?

回答

5

你想:

if (typeof(IEnumerable<IRecord>).IsAssignableFrom(propertyValue.GetType())) 
{ 
    foreach (var property in (IEnumerable<IRecord>)propertyValue) 
    { 
     var test = property; 
    } 
} 

你也可以这样做:

var enumerable = propertyValue as IEnumerable<IRecord>; 
if (enumerable != null) 
{ 
    foreach (var property in enumerable) 
    { 
     var test = property; 
    } 
} 
+1

后者通常是优选的反射。 (@尼克,而不是@mdm。) – Shibumi 2012-04-02 20:19:53

相关问题