您的位置:首页 > 编程语言 > C#

C#中的is关键字原来会做null检查

2013-08-08 16:47 323 查看
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.

呵呵,长知识了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: