C#通過屬性名稱獲取(讀取)屬性值的方法
之前在開發(fā)一個程序,希望能夠通過屬性名稱讀取出屬性值,但是由于那時候不熟悉反射,所以并沒有找到合適的方法,做了不少的重復(fù)性工作??!
然后今天我再上網(wǎng)找了找,被我找到了,跟大家分享一下。
其實原理并不復(fù)雜,就是通過反射利用屬性名稱去獲取屬性值,以前對反射不熟悉,所以沒想到啊~
不得不說反射是一種很強(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; }
}
}
如果覺得上面比較復(fù)雜了,可以看下面的簡化版。
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);
}
}
}
實質(zhì)語句只有一句:
this.GetType().GetProperty(propertyName).GetValue(this, null);
其他可以忽略。。
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
c#調(diào)用qq郵箱smtp發(fā)送郵件修改版代碼分享
c#調(diào)用qq郵箱發(fā)送郵件的方法,網(wǎng)上找到的有錯誤,這里修改了一下提供給大家使用2013-12-12
C# 7.0之ref locals and returns(局部變量和引用返回)
這篇文章主要介紹了C# 7.0之ref locals and returns,即局部變量和引用返回,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
C# 關(guān)于爬取網(wǎng)站數(shù)據(jù)遇到csrf-token的分析與解決
這篇文章主要介紹了C# 關(guān)于爬取網(wǎng)站數(shù)據(jù)遇到csrf-token的分析與解決,幫助大家更好的理解和學(xué)習(xí)c#,感興趣的朋友可以了解下2021-01-01
Unity3D UGUI實現(xiàn)縮放循環(huán)拖動卡牌展示效果
這篇文章主要為大家詳細(xì)介紹了Unity3D UGUI實現(xiàn)縮放循環(huán)拖動展示卡牌效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02

