Exemplo n.º 1
0
        public static string InvokeAnalyseMood(string methodName, string message)
        {
            try
            {
                MoodAnalyser moodAnalyzer = (MoodAnalyser)MoodAnalyserReflection.CreateMoodAnalyzerObject("MoodAnalyzerProblem.MoodAnalyzer", "MoodAnalyzer", message);

                var type = typeof(MoodAnalyser);

                //GetMethod Returns an object that represents the public method with the specified name, if found; otherwise, null.

                var analyseMoodMethod = type.GetMethod(methodName);
                // Now invoke method using meta information of method, need an instance of class and parameters as arguments
                var mood = analyseMoodMethod.Invoke(moodAnalyzer, null);
                return(mood.ToString());
            }
            catch (NullReferenceException)
            {
                // Get methods returns null incase no method is found with given methodName
                // Invoke method will throw exception
                throw new CustomMoodAnalyserException(CustomMoodAnalyserException.ExceptionType.NO_SUCH_METHOD, "No such method found");
            }
            catch (TargetInvocationException ex)
            {
                // When message is null or empty this exception is thrown
                throw ex.InnerException;
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("MOOD ANALYSER PROGRAM");
            string       message      = "i am very sad";
            MoodAnalyser moodAnalyser = new MoodAnalyser(message);

            Console.WriteLine("MOOD : {0}", moodAnalyser.AnalyseMood());
        }
Exemplo n.º 3
0
 public static object SetField(MoodAnalyser moodAnalyzer, string fieldName, string newMessage)
 {
     try
     {
         // Meta information of MoodAnalyzer
         var moodAnalyzerType = typeof(MoodAnalyser);
         // Meta information of messageField
         //GetField Returns an object that represents the field with the specified name, if found; otherwise, null.
         var messageField = moodAnalyzerType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
         messageField.SetValue(moodAnalyzer, newMessage);
         return(moodAnalyzer);
     }
     catch (NullReferenceException)
     {
         // GetField returns null incase no field is found with given fieldName
         // SetValue method will throw exception
         throw new CustomMoodAnalyserException(CustomMoodAnalyserException.ExceptionType.NO_SUCH_METHOD, "No such method found");
     }
 }