c# - Array types with same element type & rank not equal -
very simple:
var equal1 = typeof(object[]) == typeof(object).makearraytype(); var equal2 = typeof(object[]) == typeof(object).makearraytype(1); var equal3 = typeof(object[,]) == typeof(object).makearraytype(2); the assumption 3 should true, turns out equal2 false - doesn't make sense given first 2 makearraytype calls equivalent , resulting array types same.
the difference can discern explicitly passing rank of array type '1' yields
typename"object[*]"whereas omitting yields"object[]".
so thought, perhaps rank of object[] isn't 1 (even though is!) - did this:
var type1 = typeof(object[]); var type2 = type1.getelementtype().makearraytype(type1.getarrayrank()); var equal = type1 == type2; //false the types have same rank, not equal.
this scenario more current scenario try build array covariance rezolver - i'm recomposing array types walking base hierarchies , using
makearraytypeoriginal array type's rank.
so - can explain why 2 array types identical rank not considered equal?
i realise there's nuance i'm missing here, , there workarounds can use, i'm curious what's going on!
the documentation explains difference:
the common language runtime makes distinction between vectors (that is, one-dimensional arrays zero-based) , multidimensional arrays. vector, has 1 dimension, not same multidimensional array happens have 1 dimension. cannot use method overload create vector type; if rank 1, method overload returns multidimensional array type happens have 1 dimension. use makearraytype() method overload create vector types.
so basically, equal1 returns vector, , equal2 returns multidimensional array happens have rank of 1.
the 2 types treated differently in clr.
interestingly, if create instance of type, end vector again:
var type = typeof(object).makearraytype(1); // create instance length 2 var array = activator.createinstance(type, 2); console.writeline(array.gettype()); // system.object[] console.writeline(type); // system.object[*] array.createinstance shows same behaviour: if ask array lower bound of 0 , rank 1, create vector:
var array = array.createinstance(typeof(object), new[] { 2 }, new[] { 0 }); console.writeline(array.gettype()); object[] objarray = (object[]) array; // fine if change 0 non-zero value, create system.object[*] , cast fail.
Comments
Post a Comment