【发布时间】: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;但这不起作用...