有谁能向我解释一下,在下面这两种铸造场景中,铸造变量的作用为何不同?当第一个变量(双初始值)在第一个示例代码中保留其初始值时,“发件人”对象将根据它被插入的新变量更改其内容属性值?
1 ex:
double initialValue = 5;
int secValue = (int)initial;
secValue = 10;
Console.WriteLine(initial); // initial value is still 5.2 ex:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
btn.Content = "Clicked"; // "sender" objects content property is also set to "Clicked".
}发布于 2015-05-17 11:51:38
这和演员无关。这是值类型和引用类型之间的区别。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 |
+-------------+在第二个示例中,您只是简单地修改按钮的一个属性,而不是更改变量指向的对象。
https://stackoverflow.com/questions/30286620
复制相似问题