[英]How to cast from object to Generic List in C#
我有一个需要比较各种值的脚本,我需要做的一件事是将List中的值与另一个列表中的值进行比较。 但由于脚本必须使用几乎任何类型 ,我将值装入对象。
现在我的问题是:
如何从对象转换为某种类型的通用列表?
然后我如何获得该列表的长度并从该列表中检索元素?
这是我试图让它工作的尝试:
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
很感谢任何形式的帮助!
您可以尝试两种方法:
使用动态:
dynamic listVal = Convert.ChangeType( val, constructedListType );
val = listVal.Count;
或使用反射:
val = constructedListType.GetProperty("Count").GetValue(value);
在您的示例中, listVal.Count
甚至不会编译,因为listVal
是Convert.ChangeType
返回的object
,并且没有这样的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.