繁体   English   中英

C#为什么将一个类实例传递给一个接受对象作为参数并将其装回工作的方法

[英]C# Why does passing of an class instance to a method which accepts object as parameter and boxing it back work

例如,让我们考虑以下示例。

 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
 }

有人可以帮我理解这一点。 链接参考解释?

谢谢

我没有看到任何拳击正在进行。 拳击是指将值类型(例如int)转换为引用类型。 在您的示例中,传递给方法的值是引用类型( class A )。 拳击链接:

http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

所以当你调用Method (或MethodCalled ,我认为这是一个错字)时发生的一切就是该方法接受class A的参数,因为它是一个object 所有引用类型都来自object

我认为你的问题实际上归结为“作为'运营商做了什么?” 这行代码:

A newA = a as A;

逻辑上转换为这个伪代码:

A newA = null;
if (a can be cast to type A)
    newA = a;

因此,您可以看到'as'运算符将正确设置newA,因为参数的类型实际上是类A.如果您传递了class B类型的另一个对象,则as运算符将返回null(假设class B不是从class A派生class A )。 这是一个带有as运算符的示例的链接,这可能有助于解释一下:

http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM