相关疑难解决方法(0)

使用CLR中的'as'关键字进行转换

在编程接口时,我发现我正在进行大量的转换或对象类型转换.

这两种转换方法有区别吗?如果是,是否有成本差异或这对我的计划有何影响?

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)

另外,什么是"一般"首选方法?

c# clr casting

377
推荐指数
7
解决办法
7万
查看次数

标签 统计

c# ×1

casting ×1

clr ×1