日期:2014-05-17  浏览次数:21250 次

var关键字对于delegate类型不适用啊,为什么?
我写了几行小程序:

    class Program
    {
        delegate bool FunDelegate(sbyte obj);
        static void Main(string[] args)
        {
          sbyte s = 1;
          FunDelegate f = s.Equals;//这句话没问题
            var f2 = s.Equals;//为什么var会有语法错误?
        }
    }

FunDelegate f=s.Equals这一行有编译错误:error CS0815: Cannot assign method group to an implicitly-typed local variable

这到底是是什么意思呢? 不是说var关键字会自动萃取类型吗?
谢谢。

------解决方案--------------------
var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function
http://msdn.microsoft.com/en-us/library/bb384061.aspx
官网上面解释地很清楚。
------解决方案--------------------
我想是为了避免程序员犯低级的错误吧。

因为让var指向一个方法,程序员忘记打括号的可能性更大。这会导致隐蔽的错误。