在CLR中投放与使用'as'关键字 - Casting vs using the 'as' keyword in the CLR

语言: CN / TW / HK

问题:

When programming interfaces, I've found I'm doing a lot of casting or object type conversion. 在对接口进行编程时,我发现我正在做大量的转换或对象类型转换。

Is there a difference between these two methods of conversion? 这两种转换方法之间有区别吗? If so, is there a cost difference or how does this affect my program? 如果是这样,是否存在成本差异,或者这对我的计划有何影响?

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);
    }
}

Also, what is "in general" the preferred method? 另外,“一般”是什么首选方法?


解决方案:

参考一: http://stackoom.com/question/253Y
参考二: Casting vs using the 'as' keyword in the CLR
「其他文章」