【问题标题】:How to cast from object to Generic List in C#如何在 C# 中从对象转换为通用列表
【发布时间】:2017-01-27 13:03:40
【问题描述】:

我有一个脚本需要比较所有类型的值,我需要它做的一件事是将一个列表中的值与另一个列表中的值进行比较。但由于 脚本必须适用于几乎任何类型,我将值装箱到对象中。

现在我的问题是:
如何将对象转换为某种类型的通用列表?
然后如何获取该列表的长度并从该列表中检索元素?

这是我试图让它发挥作用的尝试:

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.
}

第一个用例:

 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

非常感谢任何帮助!

【问题讨论】:

  • 看来你只需要转换为System.Collections.IList
  • var listVal = Convert.ChangeType( val, constructedListType );中的var是什么类型?
  • 而不是把DOES NOT WORK,把它为什么不起作用,异常?默默失败?等等...创建一个minimal reproducible example
  • @李啊!这样我就让伯爵工作了! IList v = (IList) val; val = v.Count;
  • @JacobKrall 这是我的问题。我只想做 List myList = (List)val;但这不起作用...

标签: c# list generics casting


【解决方案1】:

您可以尝试两种方法:

使用动态:

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

或者使用反射:

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

在您的示例中,listVal.Count 甚至无法编译,因为listVal 是由Convert.ChangeType 返回的object,并且没有这样的属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多