国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

2019-10-29 21:17:14
字體:
來源:轉載
供稿:網友

之前在開發一個程序,希望能夠通過屬性名稱讀取出屬性值,但是由于那時候不熟悉反射,所以并沒有找到合適的方法,做了不少的重復性工作啊!

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

其實原理并不復雜,就是通過反射利用屬性名稱去獲取屬性值,以前對反射不熟悉,所以沒想到啊~

不得不說反射是一種很強大的技術。。

下面給代碼,希望能幫到有需要的人。

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);

其他可以忽略。。

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持VEVB武林網!


注:相關教程知識閱讀請移步到c#教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 兰考县| 临桂县| 博野县| 竹山县| 洛南县| 甘洛县| 珠海市| 宁德市| 枞阳县| 黄冈市| 绿春县| 平乡县| 隆德县| 鄂伦春自治旗| 福州市| 墨竹工卡县| 平遥县| 棋牌| 蓬溪县| 德保县| 吕梁市| 那曲县| 明光市| 抚州市| 庆阳市| 崇信县| 溧水县| 县级市| 禹州市| 拜城县| 中超| 延川县| 建始县| 镇平县| 博罗县| 无棣县| 长宁县| 井研县| 汉寿县| 定边县| 长宁县|