C#中的is关键字原来会做null检查
2013-08-08 16:47
281 查看
internal class ShouldLimitNameLengthConverter : IValueConverter { const int mIdealNameLengthMax = 20; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string) return ((string)value).Length > mIdealNameLengthMax; throw (new NotSupportedException()); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { Debug.Assert(false); throw (new NotSupportedException()); } }
在改一个用户发来的crash report,通过windbg调试dump文件,确认了crash发生在Convert函数,异常是NotSupportedException,那么原因很简单,就是value is string返回了true。这个converter是WPF的DataTemplate调用的,绑定是一个对象的Text属性,是String类型。照理说没问题啊!百思不得其解!终于查了MSDN发现,in关键字是会check
null的,只要对象为空就返回false:
An is expression evaluates totrue if the provided expression is
non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.
呵呵,长知识了!
相关文章推荐
- C#中的is关键字原来会做null检查
- C#中is与as关键字的区别
- 20151024_004_C#基础知识(C#中的访问修饰符,继承,new关键字,里氏转换,is 和 as,多态,序列化与反序列化)
- C#检查foreach判读是否为null的方法
- C#检查foreach为null判断
- C#检查foreach判读是否为null的方法
- C#中的is,as关键字
- 如何:使用 C++ 实现 C# 的 is 和 as 关键字
- C#中AS和IS关键字的用法
- 关于C#中ArcGIS Engine接口的 as 和 is 关键字
- C# null关键字用法
- C# 关键字is,as的区别
- c# 中 is 和 as 关键字的区别
- C#中的is和as关键字(摘抄)
- C#基础之is,as关键字
- C#关键字 - is 和 as
- C#中的关键字is和as
- C# 参考之文字关键字null、true、false、default 以及where
- C#中as和is关键字的作用
- C#、.Net代码精简优化(空操作符(??)、as、string.IsNullOrEmpty() 、 string.IsNullOrWhiteSpace()、string.Equals()、System.IO.Path 的用法)