简体   繁体   English

为什么装箱和拆箱不适用于方法?

[英]Why doesn't boxing and unboxing work with methods?

class Program
{
  public static void FunnyMethod(object a)
  { a = 5; }
  public static void NotSoFunnyMethod(int a)
  { a = 5; }

  public static void main(string[] args)
  {
    int number = 10;
    object obj = number;

    FunnyMethod(obj);
     Console.WriteLine(obj);

    NotSoFunnyMethod((int)obj);
    Console.WriteLine(obj);
  }
}
output : 10 in both cases

Basically I'm a little curious.基本上我有点好奇。 When you create an object instance and try to work with it outside the scope of the main method, it doesn't return the final value(5) through the other methods even though it's a reference type object.当您创建object实例并尝试在 main 方法的 scope 之外使用它时,即使它是引用类型 ZA8CFDE6331BD59EB2AC96F8911C4B66,它也不会通过其他方法返回最终值 (5)

Why is that?这是为什么?

I guess it has nothing to do with boxing, it will behave the same way for objects as well.我想它与拳击无关,它对物体的行为也一样。

When you pass a reference to a method, it cannot be changed in that method.当您传递对方法的引用时,不能在该方法中更改它。 It's because of parameters being passed by value, you can change it to reference though.这是因为参数是按值传递的,您可以将其更改为引用。

You can use the ref keyword to get 5 in both cases.在这两种情况下,您都可以使用ref关键字来获得 5。

If the int was a property of an object this would work (because both reference would point to the same object in the heap).如果 int 是 object 的属性,这将起作用(因为两个引用都指向堆中的相同 object)。

Int (even as an object) is immutable (like string) so with "a = 5" you just create a new object and erased the reference of your parameter. Int(即使作为对象)是不可变的(如字符串),因此使用“a = 5”,您只需创建一个新的 object 并删除参数的引用。 (But the calling code still have the previous reference). (但调用代码仍然有前面的引用)。

You can do what you want with the "ref" keyword:你可以用“ref”关键字做你想做的事:

    public static void FunnyMethod(ref object a)
    { a = 5; }
    public static void NotSoFunnyMethod(int a)
    { a = 5; }

    public static void Main(string[] args)
    {
        int number = 10;
        object obj = number;

        FunnyMethod(ref obj);
        Console.WriteLine(obj);

        NotSoFunnyMethod((int)obj);
        Console.WriteLine(obj);
    }

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

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