感谢您阅读我的博客,如果您现在工作、学习累了或者疲惫了,不妨聆听一下音乐,它能够减轻你的疲劳,还能够带给您一种舒适愉悦的心情。如果您认为这篇文章还不错或者有所收获,您可以在页面 右侧和底部 扫描二维码 打赏我,您的鼓励是我继续写作、分享的最大动力!

.NET 通过反射获取匿名类的属性值

实现的代码

using System;

namespace ReflectionDemo01
{
    /// <summary>
    ///     .NET 通过反射获取匿名类的属性值
    ///     LDH @ 2018-1-31
    /// </summary>
    internal class Program
    {
        private static void Main()
        {
            Console.Title = ".NET 通过反射获取匿名类的属性值";

            HowToUseReflectionToGetPropertyValue();

            Console.ReadKey();
        }

        /// <summary>
        ///     如何使用反射获取匿名类的属性值
        ///     LDH @ 2018-1-31
        /// </summary>
        private static void HowToUseReflectionToGetPropertyValue()
        {
            var student = new {Name = "LDH", Age = 28, Sex = "", Address = "上海"};

            var propertyInfoName = student.GetType().GetProperty("Name");
            if (propertyInfoName != null)
            {
                var name = propertyInfoName.GetValue(student, null);
                Console.WriteLine("姓名:{0}", name);
            }

            var propertyInfoAge = student.GetType().GetProperty("Age");
            if (propertyInfoAge != null)
            {
                var age = propertyInfoAge.GetValue(student, null);
                Console.WriteLine("年龄:{0}", age);
            }

            var propertyInfoSex = student.GetType().GetProperty("Sex");
            if (propertyInfoSex != null)
            {
                var sex = propertyInfoSex.GetValue(student, null);
                Console.WriteLine("性别:{0}", sex);
            }

            var propertyInfoAddress = student.GetType().GetProperty("Address");
            if (propertyInfoAddress != null)
            {
                var address = propertyInfoAddress.GetValue(student, null);
                Console.WriteLine("地址:{0}", address);
            }
        }
    }
}

运行结果:

posted @ 2018-01-31 13:42  Love In Winter  阅读(110)  评论(0编辑  收藏  举报
作者: LifeDecidesHappiness
出处: http://www.cnblogs.com/LifeDecidesHappiness/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,否则保留追究法律责任的权利,且在文章页面明显位置给出原文连接,如有问题,可以通过以下邮箱地址 2468881301@qq.com  联系我,非常感谢。
踏实做一个为人民服务的搬运工!
如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能,您的支持和鼓励是我继续写作、分享的最大动力!

点击关注不迷路,让我带你上高速!