【问题标题】:Different behaviours in cast operations? [duplicate]演员表操作中的不同行为? [复制]
【发布时间】:2015-05-17 11:47:01
【问题描述】:

谁能向我解释一下,为什么在下面的这两个铸造场景中,铸造变量的行为不同?虽然第一个变量(双初始值)在第一个示例代码中保留其初始值,但“发送者”对象会根据它被转换为的新变量更改其内容属性值?

第一个前任:

double initialValue = 5;

int secValue = (int)initial;

secValue = 10;

Console.WriteLine(initial); // initial value is still 5.

第二个例子:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button btn = (Button)sender;
    btn.Content = "Clicked"; // "sender" objects content property is also set to "Clicked".
}

【问题讨论】:

标签: c# casting implicit explicit sender


【解决方案1】:

这与选角无关。这是值类型引用类型之间的区别。 int 是值类型,Button 是引用类型:

int a = 1;
int b = a;  // the value of a is *copied* to b

Button btnA = ...;
Button btnB = btnA;  // both `btnA` and `btnB` point to the *same* object.

简单来说,值类型包含一个值,引用类型指的是某个对象。插图:

  a       b      btnA     btnB
+---+   +---+     |        |
| 1 |   | 1 |     |        +---------+
+---+   +---+     |                  v
                  |             +-------------+
                  +-----------> |  The button |
                                +-------------+

以下问题包含对此问题的更详细说明:


但请注意,在您的第一个示例中,您正在重新分配secValue 的值。您也可以对引用类型执行相同操作:

b = 2;
btnB = someOtherButton;

  a       b      btnA     btnB
+---+   +---+     |        |              +-------------------+
| 1 |   | 2 |     |        +------------> | Some other button |
+---+   +---+     |                       +-------------------+
                  |     +-------------+
                  +---> |  The button |
                        +-------------+

在您的第二个示例中,您只是修改了按钮的 属性,而不是更改变量指向的对象。

【讨论】:

  • 值类型在这里并不重要。 OP 正在重新分配变量;不改变它(在第一个例子中)。即使它是一个引用类型,它的行为也是一样的。
  • @SriramSakthivel 但是 OP 也假设值类型的引用语义。
  • @SriramSakthivel:感谢您的反馈,我已将其纳入我的答案(并为您的答案 +1)。
  • @YuvalItzchakov 我没看到。但简单地这个问题没有多大意义。
猜你喜欢
  • 2017-12-22
  • 2018-10-03
  • 2021-01-22
  • 1970-01-01
  • 2023-03-08
  • 2018-04-25
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多