问题
My teacher has asked me to write a program in C# to handle "Array type mismatch exception". But i couldn't find anything in the net related to that. I just want to confirm if there exists something like that.
回答1:
ArrayTypeMismatchException on MSDN
回答2:
Let’s say Class2 derives from Class1, because C# language is covariant when it comes to assigning arrays following assignment is perfectly valid
Class1[] generalizedArray;
Class2[] specializedArray = new Class2[]{new Class2(),new Class2()};
generalizedArray= specializedArray;
But half way through if you assign an element like this
generalizedArray[0]=new Class1()
Compiler won`t even issue a warning. You will get a nasty ArrayTypeMismatchException at runtime instead. This is because you can’t have two types of objects in an array like above
Read more about Covariance, contravariance and invariance in C# language in http://geekswithblogs.net/Martinez/archive/2008/12/30/covariance-contravariance-and-invariance-in-c-language.aspx
回答3:
As cited in ArrayTypeMismatchException Class on MSDN:
ArrayTypeMismatchException is thrown when the system cannot convert the element to the type declared for the array. For example, an element of type String cannot be stored in an Int32 array because conversion between these types is not supported. It is generally unnecessary for applications to throw this exception.
Use above link for example.
回答4:
Yes, it is an exception class:
Mismatch match exception
回答5:
It can happen at the run-time evaluation of argument lists. Section 7.5.1.2 C# 5.0 mentions:
• For a reference or output parameter, the variable reference is evaluated and the resulting storage location becomes the storage location represented by the parameter in the function member invocation. If the variable reference given as a reference or output parameter is an array element of a reference-type, a run-time check is performed to ensure that the element type of the array is identical to the type of the parameter. If this check fails, a System.ArrayTypeMismatchException is thrown.
One simple example given in the spec for it:
class Test
{
static void F(ref object x) {...}
static void Main() {
object[] a = new object[10];
object[] b = new string[10]; //Array covariance
F(ref a[0]); // Ok
F(ref b[1]); // ArrayTypeMismatchException because the actual element type of b is string and not object.
}
}
来源:https://stackoverflow.com/questions/3477675/is-there-something-known-as-array-type-mismatch-exception-in-c