Пример #1
0
        public virtual void Find(params Type[] types)
        {
            foreach (Type t in types)
            {
                if ((t.GetCustomAttribute <SampleAttribute>() is SampleAttribute a))
                {
                    SampleInfo info = new SampleInfo()
                    {
                        Name        = this.GetName(t),
                        Description = this.GetDescription(t),
                        Type        = t
                    };

                    Samples.Add(info);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Run a sample.
        /// </summary>
        /// <param name="sample">SampleInfo to be run.</param>
        public virtual void Run(SampleInfo sample)
        {
            // Create object, a section should be added here for constructors with parameters.
            object obj = CreateObject(sample.Type);

            // Get all methods marked to be run.
            IEnumerable <MethodInfo> methods = FindRunMethods(sample);

            // Foreach method, create parameters and invoke it.
            // Trust that the methods were returned in the order specified by the user in [Run(order:...)].
            foreach (MethodInfo mi in methods)
            {
                object result    = null;
                var    arguments = CreateArguments(mi.GetParameters());
                if (IsAsync(mi))
                {
                    var task = (mi.Invoke(obj, arguments));
                    if (task is Task <object> taskWithResult)
                    {
                        result = taskWithResult.GetAwaiter().GetResult();
                    }
                    else if (task is Task taskWithoutResult)
                    {
                        taskWithoutResult.Wait();
                        result = null;
                    }
                    else
                    {
                        throw new NotSupportedException("The return type of this async method is not supported");
                    }
                }
                else
                {
                    result = mi.Invoke(obj, arguments);
                }

                // do something with result maybe
            }
            // Check for dispose and run.
            if (FindDisposeMethod(sample) is MethodInfo dispose)
            {
                dispose.Invoke(obj, new object[] { });
            }
        }