Esempio n. 1
0
        /* The type of an object contains all the fields of an object, along with all the metadata
         * describing the object. We can use methods and objects in the System.Reflection namespace
         * to work with Type objects. The code below extract information about all the fields in the
         * Person2 type. It prints all the members of the Person2.
         * Note that the Name property has been implemented by the compiler as a pair of get and set
         * methods (set_Name and get_Name), and the class contains all the methods that are exposed
         * by an object, including ToString and, of course, the GetType method. */
        private static void InvestingatingATypeExample()
        {
            Person2 p    = new Person2();
            Type    type = p.GetType();

            foreach (MemberInfo member in type.GetMembers())
            {
                Console.WriteLine(member.ToString());
            }
        }
Esempio n. 2
0
        public static Person2 DeserializeJSONToObject(string json)
        {
            Person2      p2 = new Person2();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            DataContractJsonSerializer ser = new DataContractJsonSerializer(p2.GetType());

            p2 = ser.ReadObject(ms) as Person2;
            ms.Close();
            return(p2);
        }
Esempio n. 3
0
        /* We can use the information provided by a type to create a call to a method in that type. */
        private static void ReflectionMethodCallExample()
        {
            Person2 p = new Person2();
            Type    t = p.GetType();

            /* The code below will set the name of a person by using the set_Name behavior of the Name
             * property in the Person2 class. It does this by finding the MethodInfo for this method and
             * then calling the Invoke method on this reference. */
            MethodInfo setMethod = t.GetMethod("set_Name");

            /* The Invoke method is supplied with a reference to the Person2 that is the target of the
             * method invocation and an array of object references which will be used as the arguments
             * to that method call.
             * This code would, of course, be much slower than just setting the Name property to the value
             * "Anderson", but it illustrates the flexibility provided by reflection. A program can now
             * obtain a reference to an object, find out what behaviors that object exposes, and then
             * make use of the behaviors that it needs. */
            setMethod.Invoke(p, new object[] { "Anderson" });

            Console.WriteLine(p.Name);
        }