欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來(lái)到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁(yè) > 軟件編程 > C#教程 >

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

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C#教程|點(diǎn)擊: 次

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

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

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

不得不說(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í)也希望多多支持我們!

上一篇:詳解二維碼生成工廠

欄    目:C#教程

下一篇:C# MVC 微信支付教程系列之公眾號(hào)支付代碼

本文標(biāo)題:C#通過屬性名稱獲取(讀取)屬性值的方法

本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6082.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有