I'm fairly new to C# but have searched the web for an hour and no joy...
I need to ascertain whether an object is a non-zero index array, ie object[*]
I've tried:
if(v != null && v.GetType() == typeof(object[*]))
and if(v is object[*])
as well as overloaded methods Method(object v) and 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?
(Please don't tell me this bad code/design, it's coming from Excel so I obviously cannot change that).
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.
If you need to call GetLowerBound
you can safely cast the object to System.Array
.
If the object is really typed as object[]
and not as string[]
or some other array then this will do
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
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 !!!
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.