通过反射获取静态变量的值

转自:点击打开链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  class  Test
         {
             public  static  string  StaticPer =  "StaticPer" ;
             public  readonly  string  ReadOnlyPer =  "ReadOnlyPer" ;
             public  const  string  ConstPer =  "ConstPer" ;
 
             public  string  GetPer {  get  return  "GetPer" ; } }
             private  string  _SetPer;
             public  string  SetPer {  set  { _SetPer = value; } }
             public  string  GetSetPer {  get set ; }
 
             public  void  Ok()
             {
 
             }
 
         }
         
         
         
         var  obj =  new  Test();
             var  type = obj.GetType();
             var  p = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
 
             foreach  ( var  item  in  p)
             {
                 Console.WriteLine( "Name: {0}" , item.Name);
             }
 
             foreach  (FieldInfo field  in  type.GetFields())
             {
                 Console.WriteLine( "Field: {0}, Value:{1}" , field.Name, field.GetValue(obj));
             }
追问:
有不循环,直接根据属性名变量一下子取出来的么?
追答:
using System.Linq;

// 取出 StaticPer 属性的值

var value = type.GetFields().FirstOrDefault(f => f.Name == "StaticPer").GetValue(obj);
Console.WriteLine(value);
提问者评价
太给力了,你的回答完美地解决了我的问题,非常感谢!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值