在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
「其他文章」