我想知道是否有办法找到对象是数组还是IEnumerable,它比这更漂亮:
var arrayFoo = new int[] { 1, 2, 3 };
var testArray = IsArray(arrayFoo);
// return true
var testArray2 = IsIEnumerable(arrayFoo);
// return false
var listFoo = new List<int> { 1, 2, 3 };
var testList = IsArray(listFoo);
// return false
var testList2 = IsIEnumerable(listFoo);
// return true
private bool IsArray(object obj)
{
Type arrayType = obj.GetType().GetElementType();
return arrayType != null;
}
private bool IsIEnumerable(object obj)
{
Type ienumerableType = obj.GetType().GetGenericArguments().FirstOrDefault();
return ienumerableType != null;
}
答案 0 :(得分:7)
C#中有is
个关键字:
private bool IsArray(object obj)
{
return obj is Array;
}
private bool IsIEnumerable(object obj)
{
return obj is IEnumerable;
}
答案 1 :(得分:5)
这有帮助吗?
“是”关键字
检查对象是否与给定类型兼容。
static void Test(object value)
{
Class1 a;
Class2 b;
if (value is Class1)
{
Console.WriteLine("o is Class1");
a = (Class1)o;
// Do something with "a."
}
}
“as”关键字
尝试将值强制转换为给定类型。如果强制转换失败,则返回null。
Class1 b = value as Class1;
if (b != null)
{
// do something with b
}
<强>参考强>
“是”关键字
http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.110).aspx
“as”关键字
http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.110).aspx