.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); } } } }
运行结果:
本文作者:Love In Winter
本文链接:https://www.cnblogs.com/LifeDecidesHappiness/p/8391813.html
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!
本文链接:https://www.cnblogs.com/LifeDecidesHappiness/p/8391813.html
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!
![扫一扫,支付宝打赏](https://files.cnblogs.com/files/LifeDecidesHappiness/%E6%94%AF%E4%BB%98%E5%AE%9D.bmp)
![扫一扫,微信打赏](https://files.cnblogs.com/files/LifeDecidesHappiness/%E5%BE%AE%E4%BF%A1%E6%94%B6%E6%AC%BE%E7%A0%81.bmp)