简体   繁体   English

如何在C#中执行typeof object [*]?

[英]How to do typeof object[*] in C#?

I'm fairly new to C# but have searched the web for an hour and no joy... 我是C#的新手,但是在网上搜索了一个小时却没有任何乐趣...

I need to ascertain whether an object is a non-zero index array, ie object[*] 我需要确定对象是否为非零索引数组,即object [*]

I've tried: 我试过了:

if(v != null && v.GetType() == typeof(object[*]))

and if(v is object[*]) 和if(v是object [*])

as well as overloaded methods Method(object v) and Method(object[*] v) 以及重载的方法Method(object v)和Method(object [*] v)

All result in compilation errors. 所有这些都会导致编译错误。

As I can't cast object[*] to object[] and then test GetLowerBound(0) how the hell can I test this type? 由于无法将object [*]转换为object [],然后测试GetLowerBound(0),我该如何测试这种类型?

(Please don't tell me this bad code/design, it's coming from Excel so I obviously cannot change that). (请不要告诉我这个错误的代码/设计,它来自Excel,因此我显然无法更改)。

I think you want: 我想你要:

Array array = v as Array;
if(array != null && array.GetLowerBound(0) != 0)
{
    ...
}

Test: 测试:

var array = Array.CreateInstance(typeof(object), new[] { 3 }, new[] { 1 });
Console.WriteLine(array.GetType());
Console.WriteLine(array.GetLowerBound(0));

Output: 输出:

System.Object[*]
1

Try Type.IsArray , Type.GetArrayRank and Type.GetElementType if necessary. 如有必要,请尝试Type.IsArrayType.GetArrayRankType.GetElementType

If you need to call GetLowerBound you can safely cast the object to System.Array . 如果需要调用GetLowerBound ,则可以安全地将对象GetLowerBoundSystem.Array

If the object is really typed as object[] and not as string[] or some other array then this will do 如果确实将对象键入为object[]而不是string[]或其他数组,则可以

typeof(object[])

A placeholder for the array size is not required, since this is the normal way of declaring arrays 不需要数组大小的占位符,因为这是声明数组的常规方法

object[] myObjectArray;

EDIT: 编辑:

In your case, you could simplify the statement to 就您而言,您可以将语句简化为

if(v is object[])

since 以来

((object[])null) is object[]

yields false 产生false

 Object [] v = new Object[2];

 if (!ReferenceEquals(v, null))
          {
              if ((v.GetType() is System.Object)
                  && (v.GetType().IsArray))
              {

              }
          }

but just 'v' is initialize not your objects inside !!! 但是只是“ v”被初始化而不是您内部的对象!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM