Posts

....
Technical Blog for .NET Developers ©

Monday, July 22, 2019

Reflection : Chapter 1

.NET Reflection is the art of meta-coding, obtaining information that describes assemblies, modules and types.

By Reflection it is possible to discover the structure of an assembly, instantiating types with its methods, fields, accessors, and so on.

In this sample we get a known method in a known type: Reflection.Sample.Sample.GetMultiply:


        public decimal GetMultiply(decimal initialData, double addedData)
        {
            return (initialData * 3.14159M) / (decimal) addedData;
        }


Set the call to the function:


            Assembly asm = typeof(Sample.Sample).Assembly;

            Module module = asm.GetModule("Reflection.Sample.dll");

            Type type = module.GetType("Reflection.Sample.Sample", true, true);

            MethodInfo method = type.GetMethod("GetMultiply");

            ParameterInfo[] @params = method.GetParameters();

            Type returnType = method.ReturnType;

            var result = Activator.CreateInstance(returnType);

            object[] setParams = new object[@params.Length];

            for (int i = 0; i < @params.Length; i++)
            {
                setParams[i] = Activator.CreateInstance((@params[i]).ParameterType);

                switch (setParams[i].GetType().Name)
                {
                    case "Decimal":

                        setParams[i] = 10.40M;

                        break;

                    case "Double":

                        setParams[i] = 256.2048;

                        break;
                }
            }

            var obj = Activator.CreateInstance(type);

            result = method.Invoke(obj, setParams);