C# Why does passing of an class instance to a method which accepts object as parameter and boxing it back work
For example lets consider the following example.
class A
{
int i;
string j;
double t;
}
A a =new A();
MethodCalled(a);
void Method(object a)
{
A newA = a as A; // This will work even though Class A is down casted to System.Object
}
Can somebody please help me understand this. A link reference to explanation ?开发者_运维百科
Thanks
I don't see any boxing going on. Boxing is when a value type (e.g. int) is converted to a reference type. In your example, the value passed to the method is a reference type (class A
). Link for boxing:
http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
So all that's happening when you call Method
(or MethodCalled
, I assume that's a typo) is that the method is accepting the argument of type class A
because it is an object
. All reference types derive from object
.
I think your question really boils down to "what does the 'as' operator do?" This line of code:
A newA = a as A;
logically translates to this pseudo-code:
A newA = null;
if (a can be cast to type A)
newA = a;
So you can see that the 'as' operator will set newA correctly because the parameter's type is actually class A. If you passed another object of type class B
, the as operator would return null (assuming class B
didn't derive from class A
). Here's a link with a sample on the as operator, which might help explain a bit better:
http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx
精彩评论