.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 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!

浙公网安备 33010602011771号