C#通過(guò)屬性名稱獲取(讀取)屬性值的方法
之前在開(kāi)發(fā)一個(gè)程序,希望能夠通過(guò)屬性名稱讀取出屬性值,但是由于那時(shí)候不熟悉反射,所以并沒(méi)有找到合適的方法,做了不少的重復(fù)性工作??!
然后今天我再上網(wǎng)找了找,被我找到了,跟大家分享一下。
其實(shí)原理并不復(fù)雜,就是通過(guò)反射利用屬性名稱去獲取屬性值,以前對(duì)反射不熟悉,所以沒(méi)想到啊~
不得不說(shuō)反射是一種很強(qiáng)大的技術(shù)。。
下面給代碼,希望能幫到有需要的人。
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; }
}
}
如果覺(jué)得上面比較復(fù)雜了,可以看下面的簡(jiǎn)化版。
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);
}
}
}
實(shí)質(zhì)語(yǔ)句只有一句:
this.GetType().GetProperty(propertyName).GetValue(this, null);
其他可以忽略。。
以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!
- C#編程獲取實(shí)體類(lèi)屬性名和值的方法示例
- C# 獲取屬性名的方法
- C#實(shí)現(xiàn)讀取匿名對(duì)象屬性值的方法示例總結(jié)
- C#動(dòng)態(tài)對(duì)象(dynamic)詳解(實(shí)現(xiàn)方法和屬性的動(dòng)態(tài))
- C#實(shí)現(xiàn)獲取不同對(duì)象中名稱相同屬性的方法
- C#中使用反射遍歷一個(gè)對(duì)象屬性及值的小技巧
- C#利用反射來(lái)判斷對(duì)象是否包含某個(gè)屬性的實(shí)現(xiàn)方法
- C#通過(guò)屬性名字符串獲取、設(shè)置對(duì)象屬性值操作示例
相關(guān)文章
C#從數(shù)據(jù)庫(kù)讀取數(shù)據(jù)到DataSet并保存到xml文件的方法
這篇文章主要介紹了C#從數(shù)據(jù)庫(kù)讀取數(shù)據(jù)到DataSet并保存到xml文件的方法,涉及C#操作DataSet保存到XML文件的技巧,需要的朋友可以參考下2015-04-04
C#實(shí)現(xiàn)時(shí)間戳的簡(jiǎn)單方法
這篇文章主要介紹了C#實(shí)現(xiàn)時(shí)間戳的簡(jiǎn)單方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04
C#滑動(dòng)驗(yàn)證碼拼圖驗(yàn)證功能實(shí)現(xiàn)(SlideCaptcha)
目前網(wǎng)站上的驗(yàn)證碼機(jī)制可謂是五花八門(mén),有簡(jiǎn)單的數(shù)字驗(yàn)證,有摻雜了字母和文字的混淆驗(yàn)證,還有通過(guò)滑塊進(jìn)行的拼圖驗(yàn)證,下面這篇文章主要給大家介紹了關(guān)于C#滑動(dòng)驗(yàn)證碼拼圖驗(yàn)證功能的實(shí)現(xiàn)方法,需要的朋友可以參考下2022-04-04
C#基于正則表達(dá)式實(shí)現(xiàn)獲取網(wǎng)頁(yè)中所有信息的網(wǎng)頁(yè)抓取類(lèi)實(shí)例
這篇文章主要介紹了C#基于正則表達(dá)式實(shí)現(xiàn)獲取網(wǎng)頁(yè)中所有信息的網(wǎng)頁(yè)抓取類(lèi),結(jié)合完整實(shí)例形式分析了C#正則網(wǎng)頁(yè)抓取類(lèi)與使用技巧,需要的朋友可以參考下2017-05-05

