装箱int不会将其转换为引用类型?

时间:2017-05-16 09:07:31

标签: c# .net

纠正我,如果我错了将转换值类型转换为引用类型,那么为什么下面的代码给10输出而不是12?

public static void fun(Object obj)
    {
        obj =12;
    }
    static void Main(string[] args)
    {
        int value =10;
        Object obj = value;
        fun(obj);
        Console.WriteLine((int)obj);
    }

5 个答案:

答案 0 :(得分:3)

Because you're not actually modifying the value of obj in your Main method when you call fun. The value is given to fun and changed there and only there since it is essentially a copy of that variable, as it is being passed by value and not by reference.

Either use the ref keyword:

public static void fun(ref Object obj)
{
   obj = 12;
}
static void Main(string[] args)
{
   int value = 10;
   Object obj = value;
   fun(ref obj);
   Console.WriteLine((int)obj);
}

or make your fun method return the new value:

public static Object fun(Object obj)
{
   obj = 12;
   return obj;
}
static void Main(string[] args)
{
   int value = 10;
   Object obj = value;
   obj = fun(obj);
   Console.WriteLine((int)obj);
}

答案 1 :(得分:2)

这与装箱/拆箱无关。您只是在方法中创建一个新对象,并用它替换传递的参数。由于您没有将参数作为ref传递,因此调用代码不会受到影响。

将您的方法声明为

public static void fun(ref Object obj)

并将通话更改为

fun(ref obj);

然后输出12。

答案 2 :(得分:2)

.NET function calls pass arguments by value, not by reference (except when you use ref or out). I.e. as soon as you assign something to a function's parameter inside the function, you do not see the change outside the function. Even though for reference types you pass references around, you still pass these references by value.

答案 3 :(得分:2)

Because you are passing value to your function as value type. You should pass object as reference type.

public static void Main(string[] args)
{
   int value =10;
   Object obj = value;
   fun(ref obj);
   Console.WriteLine((int)obj);
}

public static void fun(ref Object obj)
{
    obj =12;
}

答案 4 :(得分:2)

It doesn't matter if its value type or reference type.
When you pass a variable to a function, you are assigning the parameter in the function with your variable. They both point to the same instance. but inside the function you are assigning a new value for it, so it is a new instance. the previous one of course will not change.

This is the same as:

object o = 10;
object o2 = o;
o2=12;

o is still 10, while o2 is 12

相关问题