简体   繁体   中英

Using pattern matching to match an array with a non-zero lower bound

I'm writing code that calls Excel macros via COM Automation. There is a need to handle different return types and pattern matching is perfect for that:

var result = ExcelApp.Run("MyMacro", ...);

return result switch
{
    object[,] array => ...,
    string message => ...,
    _ => throw new MyException("...")
};

Because it's Excel the arrays have a lower bound of 1 instead of 0 and this is fully supported in .NET. However, to my surprise I have discovered that when I try to perform pattern matching of a one-dimensional array with a lower bound of 1 the pattern doesn't match.

To elaborate, creating a 2×2 array with lower bounds of 1 will match the pattern object[,] , ie the following statement is true :

Array.CreateInstance(typeof(object), new[] { 2, 2 }, new[] { 1, 1 }) is object[,] array

However, creating a 1×2 array (just a normal array with two elements) with a lower bound of 1 (which is not normal) will not match the pattern object[] , ie the following statement is false :

Array.CreateInstance(typeof(object), new[] { 2 }, new[] { 1 }) is object[] array

This is surprising to me but is there a pattern that can be used to match a one-dimensional array with a non-zero lower bound?

It's odd that the rules for pattern matching arrays are different for one-dimensional arrays but because the array has a Rank property it's still possible:

return result switch
{
    Array { Rank: 1 } array => ...,
    // ... other cases
};

In case you want to convert the 1-based array (matched in array above) into a normal 0-based array it can be done like this:

array.Cast<object>().ToArray()

Because the lower bound isn't exposed as a property and instead requires a method call ( GetLowerBound() ) you can't pattern match on a specific lower bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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