最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#通過(guò)屬性名稱獲取(讀取)屬性值的方法

 更新時(shí)間:2016年12月12日 11:19:21   作者:弎吩鍾熱℃  
本文主要介紹了C#通過(guò)屬性名稱獲取(讀取)屬性值的方法,并提供了簡(jiǎn)化版代碼,具有很好的參考價(jià)值,需要的朋友可以看下

之前在開發(fā)一個(gè)程序,希望能夠通過(guò)屬性名稱讀取出屬性值,但是由于那時(shí)候不熟悉反射,所以并沒(méi)有找到合適的方法,做了不少的重復(fù)性工作?。?/p>

然后今天我再上網(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; }
 }
}

如果覺得上面比較復(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í)也希望多多支持腳本之家!

相關(guān)文章

最新評(píng)論

广平县| 汉沽区| 岳普湖县| 罗田县| 阳新县| 宁强县| 皮山县| 上栗县| 宁陵县| 上栗县| 浑源县| 砚山县| 永泰县| 沁源县| 宿迁市| 安仁县| 扶余县| 安吉县| 饶阳县| 邹城市| 二连浩特市| 咸阳市| 长宁区| 东丰县| 华安县| 抚远县| 巨野县| 来安县| 哈尔滨市| 习水县| 林口县| 桂林市| 南漳县| 蒙阴县| 天峻县| 蒙山县| 桑植县| 青冈县| 西充县| 东辽县| 阳山县|