软件编程
位置:首页>> 软件编程>> C#编程>> C#通过属性名称获取(读取)属性值的方法

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

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

标签:C#,属性值

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

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

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

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

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


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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com