c# – ‘as’关键字的用例
发布时间:2020-12-15 08:44:02 所属栏目:百科 来源:网络整理
导读:参见英文答案 Casting vs using the ‘as’ keyword in the CLR18个 我想知道,在这种情况下你会使用C#的’as’关键字,而不是转换和检查异常? 考虑这个例子: Parent obj = new Child();// Method 1:try{ Child result1 = (Child)obj;}catch (InvalidCastExc
参见英文答案 >
Casting vs using the ‘as’ keyword in the CLR18个
我想知道,在这种情况下你会使用C#的’as’关键字,而不是转换和检查异常? 考虑这个例子: Parent obj = new Child(); // Method 1: try { Child result1 = (Child)obj; } catch (InvalidCastException) { // Handle failed cast } // Method 2: if(obj is Child) { Child result2 = obj as Child; } else { // Handle failed cast } 据我所知,方法1和方法2都产生完全相同的结果. 解决方法
例外可能代价高昂并且具有隐含的goto行为.
我会做案例2,你可以节省一些指示和清晰度. Child result2 = obj as Child; if(result2 != null) { } else { // Handle failed cast } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |