【发布时间】:2016-01-21 18:43:55
【问题描述】:
我有两种类型:
public class Type1
{
public string Name { get; set; }
}
public class Type2
{
public string Name { get; set; }
}
我有一个元素列表(每个元素都是一个对象类型)。 一些元素可能是一个数组。 (数组可以是 type1[] 或 type2[])
我的目标是:
1-迭代我的元素列表
2-确定哪些是 type1[]array pr type2[] array
3-获取先前数组元素的名称值属性
这就是我所做的:
foreach (var Myobject in MyList)
{
if (myObject.GetType().IsArray)
{
var elementType = myObject.GetType().GetElementType()// should me return the element type, ie Type1 or Type2
//This is where I am stuck, I know that my object is an array but I cannot cast if in type1[] or type2[] array by using elementType
//The following is not working
elementType[] myArrat = (elementType[])myObject;
// And I don't want to hardwrite each case for each possible type like this :
Type1[] myArrat = (Type1[])myObject;
Type2[] myArrat = (Type2[])myObject;
// I want to use the elementType that I got previously
}
}
提前感谢您的帮助。
【问题讨论】:
标签: c# arrays reflection casting