首页 > 解决方案 > 从类型对象创建数组

问题描述

我正在尝试创建一个已知类型且当前设置为Type. 我已经能够创建一个IList类型,但我仍然能够将它转换为类型的数组,object[]而不是获取。

object propertyValue; //This needs to be an object since it can be set to any object
Type currentType = PropertyInfo.GetType(); //Example: System.String
propertyValue = GetArray(reader, currentType); //What would this look like to make currentType work?
//Reflection occuring later to set propertyValue to attribute of String[]

在这里,我得到了什么IList,这里的问题是不确定如何将其转换为currentType. 我也更喜欢只取回一个数组:

private IList GetArray(Reader reader, Type currentType)
{
  var returnList = createList(currentType); 
  //reader loop that appends to list
  return returnList;
}

public IList createList(Type currentType)
{
  Type genericListType = typeof(List<>).MakeGenericType(currentType);
  return (IList)Activator.CreateInstance(genericListType);
}

标签: c#arrayslistgeneric-programming

解决方案


这是一个更简单的方法:

var stringType = typeof(string);
var anArray = System.Array.CreateInstance(stringType, 5);
var arrayAsArray = (object[]) anArray;

此时,变量anArray的类型为object,但引用了一个由 5 个字符串组成的数组。该变量arrayAsArray的类型为object[],并且它引用相同的字符串数组。

What you can't get (as far as I know) is a variable that it typed MyType[] referring to an array of MyType instances if all you have is typeof(MyType). The compiler creates typed object references at compile time, you don't get to play in that space.

One of the features of the .NET Framework (or flaws, depending on how you look) is that arrays are covariant. There are lots of things that can go bad with array covariance (for example, since the compiler thinks you have an `object[]', it would let you try to add an Elephant instance into your array of strings). However, in this case, it makes your code usable, even if it is somewhat fragile.


推荐阅读