c# - 如何获取描述基本类型数组的类型?

标签 c# .net reflection types

我需要为具有指定数量索引的基本类型数组创建一个 Type 实例。本质上,我需要像下面这样的方法,我可以调用...

public Type GetArrayOfType(Type baseType, int numOfIndexes)
{
    return /* magic does here */
}

因此调用该函数会产生以下结果...

GetTypeArray(typeof(bool), 1) == typeof(bool[])
GetTypeArray(typeof(bool), 2) == typeof(bool[,])
GetTypeArray(typeof(bool), 3) == typeof(bool[,,])

我能想出的唯一解决方案是以下...

public Type GetArrayOfType(Type baseType, int numOfIndexes)
{
    List<int> indexes = new List<int>();
    for(int i=0; i<numOfIndexes; i++)
        indexes.Add(1);

    return Array.CreateInstance(baseType, indexes.ToArray()).GetType();
}

这确实有效,但必须创建所需类型的实例才能调用 GetType() 似乎并不理想。必须有一种方法可以在不创建实例的情况下生成 Type。或者有吗?

最佳答案

你可以这样做:

public Type GetArrayOfType(Type baseType, int numOfIndexes) {
    return numOfIndexes == 1 ? baseType.MakeArrayType() : baseType.MakeArrayType(numOfIndexes);
}

这里有一个小技巧:虽然你可以通过 1MakeArrayType(int) ,它要生成的类型不会MakeArrayType返回的类型相同.以下是文档的摘录:

The common language runtime makes a distinction between vectors (that is, one-dimensional arrays that are always zero-based) and multidimensional arrays. A vector, which always has only one dimension, is not the same as a multidimensional array that happens to have only one dimension. You cannot use this method overload to create a vector type; if rank is 1, this method overload returns a multidimensional array type that happens to have one dimension. Use the MakeArrayType() method overload to create vector types.

关于c# - 如何获取描述基本类型数组的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13695379/

相关文章:

c# - 使用 BinaryFormatter 反序列化我的序列化数据时出现异常

.net - 后台线程打印问题

c# - 是否有一种通用方法可以递归地检查反序列化对象的空字段?

c# - 在 Windows Phone map 控件上禁用平移和缩放事件

c# - 一个或两个 MVC 项目?

c# - 在 C# 中发现串行端口

c# - 使用 C# WinForms 的透明图像

Java 反射(reflect)方法作用域变量

c# - 从哈希表创建对象 C#

c# - 提交后 ASP.Net MVC View 下拉列表未绑定(bind)到模型(发布)