C#通过属性名称获取(读取)属性值的方法

作者:弎吩锺熱℃ 时间:2023-10-10 11:49:06 

之前在开发一个程序,希望能够通过属性名称读取出属性值,但是由于那时候不熟悉反射,所以并没有找到合适的方法,做了不少的重复性工作啊!

然后今天我再上网找了找,被我找到了,跟大家分享一下。

其实原理并不复杂,就是通过反射利用属性名称去获取属性值,以前对反射不熟悉,所以没想到啊~

不得不说反射是一种很强大的技术。。

下面给代码,希望能帮到有需要的人。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PropertyNameGetPropertyValueDemo
{
class Program
{
 static void Main(string[] args)
 {
  Person ps = new Person();
  ps.Name = "CTZ";
  ps.Age = 21;
  Demo dm = new Demo();
  dm.Str = "String";
  dm.I = 1;
  Console.WriteLine(ps.GetValue("Name"));
  Console.WriteLine(ps.GetValue("Age"));
  Console.WriteLine(dm.GetValue("Str"));
  Console.WriteLine(dm.GetValue("I"));
 }
}
abstract class AbstractGetValue
{
 public object GetValue(string propertyName)
 {
  return this.GetType().GetProperty(propertyName).GetValue(this, null);
 }
}
class Person : AbstractGetValue
{
 public string Name
 { get; set; }

public int Age
 { get; set; }
}
class Demo : AbstractGetValue
{
 public string Str
 { get; set; }
 public int I
 { get; set; }
}
}

如果觉得上面比较复杂了,可以看下面的简化版。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GetValue
{
class Program
{
 static void Main(string[] args)
 {
  Person ps = new Person();
  ps.Name = "CTZ";
  ps.Age = 21;

Console.WriteLine(ps.GetValue("Name"));
  Console.WriteLine(ps.GetValue("Age"));
 }
}
class Person
{
 public string Name
 { get; set; }

public int Age
 { get; set; }
 public object GetValue(string propertyName)
 {
  return this.GetType().GetProperty(propertyName).GetValue(this, null);
 }
}
}

实质语句只有一句:

this.GetType().GetProperty(propertyName).GetValue(this, null);

其他可以忽略。。

来源:http://www.cftea.com/c/2012/10/5657.asp

标签:C#,属性值
0
投稿

猜你喜欢

  • Android自定义View之渐变色折线图的实现

    2023-09-23 21:43:03
  • C#在Excel表格中插入、编辑和删除批注

    2023-01-12 13:52:20
  • sharding-jdbc5.0.0实现分表实践

    2023-12-07 10:12:26
  • C#操作Excel相关方法总结

    2021-06-22 12:00:48
  • WPF仿三星手机充电界面实现代码

    2021-09-16 06:20:44
  • Android应用中Back键的监听及处理实例

    2022-09-26 02:00:47
  • javafx实现时钟效果

    2022-09-10 02:23:31
  • C#序列化与反序列化实例

    2023-05-05 21:05:27
  • Java中checkbox实现跨页多选的方法

    2023-10-14 11:01:20
  • Android中复制图片的实例代码

    2023-01-07 21:34:26
  • Android TV 3D卡片无限循环效果

    2022-03-26 04:06:48
  • 如何利用Jenkins + TFS为.Net Core实现持续集成/部署详解

    2022-11-12 06:14:32
  • Spring Boot(二)之web综合开发

    2022-09-10 18:52:25
  • 浅谈Android Studio 4.1 更新内容

    2021-09-17 11:27:30
  • Java实现中英文词典功能

    2021-06-20 18:25:56
  • 如何实现Spring Event(异步事件)

    2023-08-23 05:06:47
  • Mybatis插件之自动生成不使用默认的驼峰式操作

    2023-11-19 01:20:03
  • Java模拟计算机的整数乘积计算功能示例

    2022-01-30 19:25:51
  • Android中使用TextView实现高仿京东淘宝各种倒计时效果

    2021-05-26 21:32:26
  • C# 标准事件流实例代码

    2022-06-21 16:29:14
  • asp之家 软件编程 m.aspxhome.com