【发布时间】:2018-08-23 22:30:26
【问题描述】:
我正在尝试创建一个已知类型且当前设置为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);
}
【问题讨论】:
-
我认为您需要
Invoke适当的ToArray方法。 -
另一种选择,看看我对stackoverflow.com/questions/51679179/…的回答。第二个选项为您提供对
List<object>的引用,您可以在其上调用ToArray()。但是,基础列表是正确的类型。我不知道有什么方法可以获得正确类型的对象引用 (List<MyType>),只有List<object>类型的引用 -
我试图编辑我的评论,但没有时间。我的答案中的代码调用
.ToList(),但可以轻松调用ToArray()。很快,您有一个MyType[]类型的对象,但是,您无法获得对以这种方式键入的对象的引用;它将输入object[]。我不知道有什么方法可以获取正确类型的对象引用(又名变量)。
标签: c# arrays list generic-programming