在C# (范例)中,使用的是安全Casting
Jiaoyang75
・2 分钟阅读
在C#中进行强制转换是告诉编译器进行显式转换,以便将对象的类型从一个转换为另一个,并且通过显式表示您意识到在操作期间可能会截断数据。例如:将decimal
转换为float
。
让我们来看看这个例子
private void button1_Click(object sender, EventArgs e)
{
Button button = (Button)sender; // doing an explicit cast here
button.Text ="Processing...";
}
如果不再由Button
类型调用事件处理程序,则上述代码的问题就会引发InvalidCastException
。
C#提供了两个解决方案
使用as
private void button1_Click(object sender, EventArgs e)
{
Button button = sender as Button;
if (button != null)
{
button.Text ="Processing...";
}
else
{
//Do what you need to do here
}
}
使用is
private void button1_Click(object sender, EventArgs e)
{
if (sender is Button)
{
Button button = (Button)sender;
button.Text ="Processing...";
}
else
{
//Do what you need to do here
}
}
现在,没有InvalidCastException
了。
现在你应该使用什么,这是你应该考虑的下一件事,即as或is,或者快速失败,并且捕获InvalidCastException ,答案是它取决于你和你的应用程序,看一下这个StackOverflow回答 更多关于使用什么的讨论。
引用
- C#中的防御性编码,from pluralsight
- 如何:安全地使用as和is操作符(C#编程指南),来自msdn,