zoukankan      html  css  js  c++  java
  • C#中的is关键字原来会做null检查


        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.

    呵呵,长知识了!






  • 相关阅读:
    2012年浙大:Hello World for U
    noip2011普及组:统计单词
    noip2013提高组:积木大赛
    蓝桥杯:错误票据
    C#知识点
    疑问
    C#多态
    SQLServer导入Excel,复杂操作
    SQLServer数据库基本操作,导入Excel数据
    C#基础学习
  • 原文地址:https://www.cnblogs.com/puncha/p/3876890.html
Copyright © 2011-2022 走看看