gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:09:09 24 4
gpt4 key购买 nike

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

 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,我认为这是一个错字)时发生的所有事情是该方法正在接受 A 类类型的参数 因为它是一个对象。所有引用类型都派生自 object

我认为您的问题实际上可以归结为“'as' 运算符的作用是什么?”这行代码:

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 派生的)。这是 as 运算符示例的链接,这可能有助于更好地解释:

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

关于C# 为什么将类实例传递给接受对象作为参数并将其装箱回来的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7313940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com