C#如何判断一个对象是否是多维数组 [英] C# How to check if an object is a multi-dimensional array

查看:61
本文介绍了C#如何判断一个对象是否是多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C# 的新手.我在 C# 中有一个对象,如何检查它是单维数组还是多维数组?

I am a newcomer to C#. I have an Object in C#, how to check if it is an single or multi-dimensional array?

int[,] array = new int[2,3];
object obj = (object) array;
if(obj is Array)
{
    if(obj.Rank==2) // I need to cast obj to array first in order to call Rank
    {
        //do something
    }
}

推荐答案

有两种主要方法可以实现这一点.通过 casting objArray 如您所建议的:

There are two main ways to accomplish this. Either by casting obj to an Array as you suggested:

if(obj is Array && ((Array)obj).Rank == 2)
{
    //do something
}

或使用 as 运算符:

Or using the as operator:

var arr = obj as Array;
if(arr != null && arr.Rank == 2)
{
    //do something
}

请注意,在这两个解决方案中,我使用 条件 AND 运算符 (&&) 为简单起见.如果左侧评估为 true,这将仅评估右侧.

Note that in both these solutions, I've combined the two if's together using the conditional AND operator (&&) for simplicity. This will only evaluate this right hand side if the left hand side evaluates to true.

这篇关于C#如何判断一个对象是否是多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆