什么时候应该在C#中使用as关键字?
发布时间:2020-12-15 06:27:54 所属栏目:百科 来源:网络整理
导读:当您想要更改大多数时间的类型时,您只需要使用传统的演员. var value = (string)dictionary[key]; 这是好的,因为: 这是快的 如果有什么不对,它会抱怨(而不是给对象是空的异常) 那么什么是使用的一个很好的例子,因为我真的不能真正发现或想到适合它的东西?
当您想要更改大多数时间的类型时,您只需要使用传统的演员.
var value = (string)dictionary[key]; 这是好的,因为: 这是快的 那么什么是使用的一个很好的例子,因为我真的不能真正发现或想到适合它的东西? 注意:实际上,我认为有时候编译器会阻止使用作品(泛型相关?)的演员. 解决方法
使用,当它对一个对象不是你想要的类型有效,并且你想采取不同的方式,如果它是.例如,在一些伪代码中:
foreach (Control control in foo) { // Do something with every control... ContainerControl container = control as ContainerControl; if (container != null) { ApplyToChildren(container); } } 或者LINQ to Objects中的优化(很多例子): public static int Count<T>(this IEnumerable<T> source) { IList list = source as IList; if (list != null) { return list.Count; } IList<T> genericList = source as IList<T>; if (genericList != null) { return genericList.Count; } // Okay,we'll do things the slow way... int result = 0; using (var iterator = source.GetEnumerator()) { while (iterator.MoveNext()) { result++; } } return result; } 所以使用像一个是一个演员.以前几乎总是使用无效检查. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |