请考虑以下代码:
void Handler(object o, EventArgs e)
{
// I swear o is a string
string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3
}
Run Code Online (Sandbox Code Playgroud)
三种类型的铸造之间有什么区别(好吧,第三种不是铸造,但是你得到了意图).应该首选哪一个?
在编程接口时,我发现我正在进行大量的转换或对象类型转换.
这两种转换方法有区别吗?如果是,是否有成本差异或这对我的计划有何影响?
public interface IMyInterface
{
void AMethod();
}
public class MyClass : IMyInterface
{
public void AMethod()
{
//Do work
}
// Other helper methods....
}
public class Implementation
{
IMyInterface _MyObj;
MyClass _myCls1;
MyClass _myCls2;
public Implementation()
{
_MyObj = new MyClass();
// What is the difference here:
_myCls1 = (MyClass)_MyObj;
_myCls2 = (_MyObj as MyClass);
}
}
Run Code Online (Sandbox Code Playgroud)
另外,什么是"一般"首选方法?
可能重复:
使用CLR中的'as'关键字进行转换
这两个演员之间究竟有什么区别?
SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;
Run Code Online (Sandbox Code Playgroud)
通常,它们都应该显式转换为指定的类型?