Exemplo n.º 1
0
        private static string GetComponentStatusReport(GetStatus status)
        {
            if (status == null)
            {
                return(null);
            }

            StringBuilder report = new StringBuilder();

            Delegate[] arrayOfDelegates = status.GetInvocationList();

            foreach (GetStatus getStatus in arrayOfDelegates)
            {
                try
                {
                    report.AppendFormat($"{getStatus()}{Environment.NewLine}{Environment.NewLine}");
                }
                catch (InvalidOperationException e)
                {
                    object component = getStatus.Target;
                    report.AppendFormat(
                        "Failed to get status from{1}{2}{0} Error{3}{0}{0}",
                        Environment.NewLine,
                        ((component == null) ? "" : component.GetType() + "."),
                        getStatus.Method.Name,
                        e.Message);
                }
            }
            return(report.ToString());
        }
Exemplo n.º 2
0
    // Method that queries several components and returns a status report
    private static String GetComponentStatusReport(GetStatus status)
    {
        // If the chain is empty, there’s is nothing to do.
        if (status == null)
        {
            return(null);
        }

        // Use this to build the status report.
        StringBuilder report = new StringBuilder();

        // Get an array where each element is a delegate from the chain.
        Delegate[] arrayOfDelegates = status.GetInvocationList();

        // Iterate over each delegate in the array.
        foreach (GetStatus getStatus in arrayOfDelegates)
        {
            try {
                // Get a component's status string, and append it to the report.
                report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
            }
            catch (InvalidOperationException e) {
                // Generate an error entry in the report for this component.
                Object component = getStatus.Target;
                report.AppendFormat(
                    "Failed to get status from {1}{2}{0}   Error: {3}{0}{0}",
                    Environment.NewLine,
                    ((component == null) ? "" : component.GetType() + "."),
                    getStatus.GetMethodInfo().Name, e.Message);
            }
        }

        // Return the consolidated report to the caller.
        return(report.ToString());
    }
Exemplo n.º 3
0
        private static String GetComponentStatusReport(GetStatus status)
        {
            // 如果委托链为空,就不进行任何操作
            if (status == null)
                return null;

            StringBuilder report = new StringBuilder();

            Delegate[] arrayOfDelegates = status.GetInvocationList();

            // 遍历数组中的每一个委托
            foreach (GetStatus getStatus in arrayOfDelegates)
            {
                try
                {
                    report.AppendFormat("{0} {1} {1}", getStatus(), Environment.NewLine);
                }
                catch(InvalidOperationException e)
                {
                    Object component = getStatus.Target;
                    report.AppendFormat("Failed to get status from {1} {2} {0}  Error: {3} {0} {0}",
                        Environment.NewLine,
                        ((component == null) ? "" : component.GetType() + "."),
                        getStatus.Method.Name,
                        e.Message);
                }
            }

            return report.ToString();
        }
Exemplo n.º 4
0
    // Метод запрашивает состояние компонентов и возвращает информацию
    private static String GetComponentStatusReport(GetStatus status)
    {
        // Если цепочка пуста, ничего делать не нужно
        if (status == null)
        {
            return(null);
        }
        // Построение отчета о состоянии
        StringBuilder report = new StringBuilder();

        // Создание массива из делегатов цепочки
        Delegate[] arrayOfDelegates = status.GetInvocationList();
        // Циклическая обработка делегатов массива
        foreach (GetStatus getStatus in arrayOfDelegates)
        {
            try
            {
                // Получение строки состояния компонента и добавление ее в отчет
                report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
            }
            catch (InvalidOperationException e)
            {
                // В отчете генерируется запись об ошибке для этого компонента
                Object component = getStatus.Target;
                report.AppendFormat(
                    "Failed to get status from {1}{2}{0} Error: {3}{0}{0}",
                    Environment.NewLine,
                    ((component == null) ? "" : component.GetType() + "."),
                    getStatus.Method.Name,
                    e.Message);
            }
        }
        // Возвращение сводного отчета вызывающему коду
        return(report.ToString());
    }
Exemplo n.º 5
0
        private static string GetComponentStatusReport(GetStatus getStatus)
        {
            if (getStatus == null)
            {
                return("delegate is null");
            }

            StringBuilder sb = new StringBuilder();

            Delegate[] arrayOfDelegates = getStatus.GetInvocationList();

            foreach (GetStatus status in arrayOfDelegates)
            {
                try
                {
                    sb.AppendFormat("{0}{1}{1}", status(), Environment.NewLine);
                }
                catch (Exception e)
                {
                    object component = status.Target;
                    sb.AppendFormat("failed to get status from {0}{2}{0}   error:{3}{0}{0}", Environment.NewLine,
                                    component == null ? "" : component.GetType() + ".", status.Method.Name, e.Message);
                }
            }
            return(sb.ToString());
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            GetStatus getStatus = null;

            getStatus += new GetStatus(new Light().Switch);
            getStatus += new GetStatus(new Light().Switch);
            getStatus += new GetStatus(new Fan().Speed);
            getStatus += new GetStatus(new Fan().Speed);

            /* 委托类型的Invoke方法包含了对数组中的所有项进行遍历的代码
             * 这是一个很简单的算法,尽管这个简单的算法足以应付很多情形,但是也有局限
             * 这个简单的算法只是顺序调用链中的每一个委托,所以一个委托对象出现问题,链中的所有后续对象都无法调用
             * 因此,MulticastDelegate类提供了一个实例方法GetInvocationList,用于显式调用链中每一个委托
             */

            Delegate[] delegates = getStatus.GetInvocationList();
            foreach (GetStatus status in delegates)
            {
                try
                {
                    Console.WriteLine(status());
                }
                catch (InvalidOperationException e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(status.Target);
                }
            }

            Console.ReadKey();
        }
Exemplo n.º 7
0
        /// <summary>
        ///    Запрашивание состояния у компонентов делегата GetStatus
        /// </summary>
        /// <param name="status">Делегат GetStatus</param>
        /// <returns>Отчет</returns>
        private static string GetComponentStatusReport(GetStatus status)
        {
            // Если цепочка пуста, действий не нужно
            if (status == null)
            {
                return(null);
            }

            // Построение отчета о состоянии
            StringBuilder report = new StringBuilder();

            // Создание массива из делегатов цепочки
            var delegates = status.GetInvocationList();

            foreach (var getStat in delegates.Cast <GetStatus>())
            {
                try
                {
                    report.AppendFormat("{0}{1}{1}", getStat(), Environment.NewLine);
                }
                catch (InvalidOperationException e)
                {
                    var component = getStat.Target;
                    report.AppendFormat("Failed to get status from {1}{2}{0} Error: {3}{0}{0}", Environment.NewLine,
                                        component == null ? "" : component.GetType() + ".", getStat.Method.Name, e.Message);
                }
            }

            return(report.ToString());
        }
Exemplo n.º 8
0
 // Метод запрашивает состояние компонентов и возвращает информацию
 private static String GetComponentStatusReport(GetStatus status)
 {
     // Если цепочка пуста, ничего делать не нужно
     if (status == null) return null;
     // Построение отчета о состоянии
     StringBuilder report = new StringBuilder();
     // Создание массива из делегатов цепочки
     Delegate[] arrayOfDelegates = status.GetInvocationList();
     // Циклическая обработка делегатов массива
     foreach (GetStatus getStatus in arrayOfDelegates)
     {
         try
         {
             // Получение строки состояния компонента и добавление ее в отчет
             report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
         }
         catch (InvalidOperationException e)
         {
             // В отчете генерируется запись об ошибке для этого компонента
             Object component = getStatus.Target;
             report.AppendFormat(
             "Failed to get status from {1}{2}{0} Error: {3}{0}{0}",
             Environment.NewLine,
             ((component == null) ? "" : component.GetType() + "."),
             getStatus.Method.Name,
             e.Message);
         }
     }
     // Возвращение сводного отчета вызывающему коду
     return report.ToString();
 }
Exemplo n.º 9
0
   // Method that queries several components and returns a status report
   private static String GetComponentStatusReport(GetStatus status) {

      // If the chain is empty, there’s is nothing to do.
      if (status == null) return null;

      // Use this to build the status report.
      StringBuilder report = new StringBuilder();

      // Get an array where each element is a delegate from the chain.
      Delegate[] arrayOfDelegates = status.GetInvocationList();

      // Iterate over each delegate in the array. 
      foreach (GetStatus getStatus in arrayOfDelegates) {

         try {
            // Get a component's status string, and append it to the report.
            report.AppendFormat("{0}{1}{1}", getStatus(), Environment.NewLine);
         }
         catch (InvalidOperationException e) {
            // Generate an error entry in the report for this component.
            Object component = getStatus.Target;
            report.AppendFormat(
               "Failed to get status from {1}{2}{0}   Error: {3}{0}{0}",
               Environment.NewLine,
               ((component == null) ? "" : component.GetType() + "."),
               getStatus.GetMethodInfo().Name, e.Message);
         }
      }

      // Return the consolidated report to the caller.
      return report.ToString();
   }