2012-04-02 8 views
2

オブジェクトをIEnumerableにunboxしたいと思います。オブジェクトにIEnumerableを割り当てることができるかどうかを確認し、そうであればオブジェクトの値をループしたいかどうかをチェックします。しかし、私は次の操作を実行したとき:IEnumerableにオブジェクトをunboxしようとすると、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 

どのように私はIEnumerableをするPropertyValueを割り当てることができますか?あなたが欲しい

答えて

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

後者は、一般的に反射することが好ましいです。 (@Niek、@mdmではなく) – Shibumi

関連する問題