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

来源:互联网 发布:淘宝店铺怎么进货 编辑:程序博客网 时间:2024/05/29 15:34


    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 isnon-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

呵呵,长知识了!






原创粉丝点击