我有一个需要比较各种值的脚本,我需要做的一件事就是将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
非常感谢任何帮助!
答案 0 :(得分:0)
您可以尝试两种方法:
使用动态:
dynamic listVal = Convert.ChangeType( val, constructedListType );
val = listVal.Count;
或使用反射:
val = constructedListType.GetProperty("Count").GetValue(value);
在您的示例中,listVal.Count
甚至无法编译,因为listVal
是由object
返回的Convert.ChangeType
,并且没有此类属性。