在编程接口时,我发现我正在进行大量的转换或对象类型转换.
这两种转换方法有区别吗?如果是,是否有成本差异或这对我的计划有何影响?
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)
另外,什么是"一般"首选方法?
在我看来,is运营商有点不一致.
bool Test()
{
// Returns false, but should return true.
return null is string;
}
Run Code Online (Sandbox Code Playgroud)
一个人希望该null值属于任何引用(或可空)类型.事实上,C#语言规范说明了支持这种假设的东西,例如(6.1.6隐式引用转换):
隐式引用转换是:
...
•从null文本到任何引用类型.
说明(7.10.10 is运算符)中的is运营商开始通过说表达(E is T)将导致真正的当从引用转换E到T存在的,但随后笔者通过时明确排除的情况下继续E为null文字或具有null价值.
他们为什么这样做?这对我来说似乎违反直觉.