c# - 如何检查反射类型是否为数组

标签 c# arrays reflection typeof

我正在使用反射读取 xml 文件并不断遇到错误,告诉我无法将字符串转换为字符串 [](我不想这样做!)我认为我的原因问题是我无法判断对象的类型是否为数组。下面是我目前正在使用的(不能正常工作)但我也尝试使用 if(mi[i].GetType() == typeof(string[])) 哪个也不起作用..

MemberInfo[] mi = objType.GetProperties();
for (int i = 0; i < mi.Length; i++)
{
  if (mi[i].GetType().IsArray)
  {
  }
  else
  {
   //Code path is running through here
  }

文件被正确读入..

编辑:我认为我最好将结构添加到我的 objType 中以更好地解释..

objType 是一个包含 string[] 变量的类,在本例中称为 mi[i]

最佳答案

您需要在 MemberInfo 上使用 PropertyType 而不是 GetType() 来获取属性的基础类型。

var mi = objType.GetProperties();
for (int i = 0; i < mi.Length; i++)
{
    var type = mi[i].PropertyType;
    //Check for string array
    if (type.IsArray && type.GetElementType() == typeof(string))
    {
    }
}

或者你可以做

if(type == typeof(string[]))
{
}

关于c# - 如何检查反射类型是否为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13818298/

相关文章:

c# - 检测何时在 Windows 窗体的标题栏中按下帮助按钮?

c# - MEF 插件找不到引用的库

c - 如何使用 MPI 传递带有动态数组的自定义结构?

php - 我的 IF 语句有问题

c# - 制作类型集合并对其进行检查的最佳方法

c# - 文本框输入键事件在 WPF 中不起作用

c# - 如何将任何方法作为参数传递给另一个函数

java - 两个代码片段的数组赋值输出表现不同

json - 如何仅使用消息描述符将 protobuf 线格式转换为 JSON?

C#/vb.net 类型不匹配通过反射查找构造函数(Integer() vs System.Int32[])