码迷,mamicode.com
首页 > 其他好文 > 详细

可否定义拥有返回值的方法的委托链

时间:2014-08-26 13:23:26      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   使用   io   strong   for   

分析问题

  委托的方法可以是无返回的方法,也可以是有返回值的方法。回顾一下委托的使用:

  

Meth a=new Meth(Method1);
a+=new Meth(Method2);
a+=new Meth(Method3);
int returnVal=a();

   当使用类似的代码时,委托链表中各个方法的返回值起了冲突,最后一行代码只从委托中取得一个返回值,而事实上该委托链表包含三个方法,而每个方法都具有一个返回值。读者将会看到,当这样使用委托时,只有委托链表上最后被调用的方法返回值才被返回。以下代码展示了这一特性。

using System;
namespace Test
{
    public delegate string GetStringDelegate();
    class DelegateReturn
    {

        static void Main()
        {
            GetStringDelegate _myDelegate1 = new GetStringDelegate(GetTimeString);
            _myDelegate1 += GetTypeName;
            _myDelegate1 += GetSelfDefinedString;
            Console.WriteLine(_myDelegate1());

            GetStringDelegate _myDelegate2 = new GetStringDelegate(GetSelfDefinedString);
            _myDelegate2 += GetTypeName;
            _myDelegate2 += GetTimeString;
            Console.WriteLine(_myDelegate2());

            GetStringDelegate _myDelegate3 = new GetStringDelegate(GetSelfDefinedString);
            _myDelegate3 += GetTimeString;
            _myDelegate3 += GetTypeName;
            Console.WriteLine(_myDelegate3());

            Console.Read();
        }

        static string GetTimeString()
        {
            return DateTime.Now.ToString();
        }

        static string GetTypeName()
        {
            return typeof(DelegateReturn).ToString();
        }

        static string GetSelfDefinedString()
        {
            return "我是字符串";
        }
    }
}

  下面是这段程序的执行结果:

  bubuko.com,布布扣

  正如读者所看到的,虽然委托链中所有的方法都被正确执行,但委托的使用者只得到了最后一个方法所返回的值。这个结果非常糟糕,丢失大部分的方法返回值可能会造成很大的麻烦。在一些程序中,往往不会采用异常机制,而是返回一个非0的正数来告诉使用者方法执行不成功。如果该方法被添加到一个委托链的中间,那这个方法的返回值很可能就被丢失了,在这种情况下,程序员需要手动地执行委托链中的每个方法。下面笔者重写了以上代码的Main方法。

static void Main()
        {
            GetStringDelegate _myDelegate1 = new GetStringDelegate(GetTimeString);
            _myDelegate1 += GetTypeName;
            _myDelegate1 += GetSelfDefinedString;

            foreach (Delegate d in _myDelegate1.GetInvocationList())
            {
                Console.WriteLine(d.DynamicInvoke());
            }

            Console.Read();
        }

  在这种情况下,委托链中每个方法的返回值都不会丢失,下面是程序的执行结果:

bubuko.com,布布扣

答案

  委托可以是带有返回值的方法,但多于一个带返回值的方法被添加到委托链中时,程序员需要手动地调用委托链上的每个方法,否则委托使用者将只能得到委托链上最后一个被执行方法的返回值。

 

可否定义拥有返回值的方法的委托链

标签:style   blog   http   color   os   使用   io   strong   for   

原文地址:http://www.cnblogs.com/wangjinpeng-study/p/3936955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!