2017-01-27 3 views
1

の値をすべて比較するのスクリプトがあります。リストから値を別のリストの値と比較する必要があります。しかし、スクリプトはかなり多くのタイプので動作しなければならないので、オブジェクトに値をボクシングしています。Cからオブジェクトを汎用リストにキャストする方法

私の問題は次のとおりです。
オブジェクトから特定のタイプの汎用リストにキャストする方法を教えてください。
次に、そのリストの長さを取得し、そのリストから要素を取得するにはどうすればよいですか?特定の要素の比較 -

type = typeof(List<string>); //In reality I'm getting this via Reflection 
subElement = -2; //makes it compare length of Lists 
value = 3; 
bool match = CompareValue(new List<string>() { "one", "two", "three"}); //should return true since the length of the list is 3 

セカンドユースケース:

type = typeof(List<int>); //In reality I'm getting this via Reflection 
subElement = 3; //compare the 3rd element in the list 
value = 7f; 
bool match = CompareValue(new List<float>() { 3f, 4.5f, 7f, 10.4f, 22.6f }); //should return true because the value of the 3rd element is 7f 

任意の助けを

Type type; 
int subElement; 
object value; //holds the value 

public virtual bool CompareValue(object val) { //compare value against val 
    //LIST 
    if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { 
      if(subElement == -2) { //Compare against COUNT 
       var listType = typeof(List<>); 
       var constructedListType = listType.MakeGenericType(type.GetGenericArguments()[0]); //get the type inside the list 
       var listVal = Convert.ChangeType(val, constructedListType); 
       val = listVal.Count; //DOES NOT WORK :(
       return value == val; 
      } else if(subElement >= 0) { //Compare against SPECIFIC ELEMENT 
       tempType = tempType.GetGenericArguments()[0]; //Get the type inside the List 
       List<object> list = ((List<object>)val); //DOES NOT WORK 
       if(list.Count >= subElement) return false; 
       val = Convert.ChangeType(list[subElement], tempType); 
       return value == val; 
      } 
     } //else if other types, etc., etc. 
} 

まずユースケースを:

は、ここでそれが動作するようになっての私の試みです非常に感謝しています!

はダイナミックの使用::

dynamic listVal = Convert.ChangeType(val, constructedListType); 
val = listVal.Count; 

や反射を使用して:あなたは二つのアプローチしようとすることができ

+3

'System.Collections.IList'にキャストする必要があるようです。 – Lee

+0

'var 'の型は' var listVal = Convert.ChangeType(val、constructListType); '? –

+1

'DOES NOT WORK'を置くのではなく、なぜそれが動作しないのか、例外を入れますか?静かに失敗する? etc ... [MCVE]を作成します。 – TheLethalCoder

答えて

0

あなたの例では

val = constructedListType.GetProperty("Count").GetValue(value); 

listValがあるとして、listVal.Countにも、コンパイルされないでしょうobjectConvert.ChangeTypeによって返され、このようなプロパティはありません。

関連する問題