Anonymous Objects and Dynamic Types

 class Program
    {
        static void Main(string[] args)
        {
            //When a temporary object needs to be used, use an anonymous object
            dynamic p = new { Name="Zhang San", Age=50};//Receive
            var t through dynamic type = new { Name = "Zhang San", Age = 50 }; //Receive
            var v = p through anonymous type;
            aaa(new { Name = "Zhang San", Age = 50 });
            Console.ReadKey();
        }


        public static void aaa(object a) {
            //When an anonymous object is received through object, the value can only be obtained through reflection
           Type s = a.GetType();
           PropertyInfo pInfoName = s.GetProperty("Name");
           PropertyInfo pInfoAge = s .GetProperty("Age");
           object name = pInfoName.GetValue(a, null);
           object age = pInfoAge.GetValue(a, null);


           PropertyInfo[] props = s.GetProperties();
            //Directly convert the object object to dynamic type to get the value
            dynamic p = a ;
            //object cannot be directly cast to anonymous type
            var d = a;
            Console.WriteLine(p.Name);
            Console.WriteLine(p.Age);
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324845101&siteId=291194637