为什么不能将int []数组传递给接受C#中的object []数组的方法?

时间:2017-03-28 06:36:34

标签: c# arrays object boxing

我知道c#中的所有内容都是从object继承的,所以在我的理解中你应该始终能够将对象类型的变量替换为任何其他类型的变量。请考虑此代码以及我在评论中提出的问题:

//Methods declaration
public static void ArrayMethod(object[] a)
{
}
public static void Method(object a)
{
}

//In main method
string[] strArray = { "one", "two" };
int[] intArray = { 1, 3};

ArrayMethod(intArray);   //Here is an error saying "cannot convert from int[] to object[]" (Why is that the case? isn't int of type object?)
ArrayMethod(strArray);  //Here there is no error so apparently converting from string[] to object[] is not an issue (Why is that the case, giving previous error?)

int intVar = 2;    
Method(intVar); //No error here, so apparently converting/boxing from int to object is not an issue as well (Again why is that the case, giving the first error?)    

0 个答案:

没有答案