C# 反射获取属性

本人用C#在封装底层的时候需要获取属性,想到了用反射:

百度过后总结下
Type type = typeof(ContentInfo); //ContentInfo为类名
var memberInfos = type.GetProperties();   //可以获取ContentInfo所有属性,是个数组

通过遍历可得到各个属性

比如:foreach (var member in memberInfos)

而  

type.GetProperty("Property1"); //获取指定名称的属性

 

另外,我在查资料的时候,看过这样一个例子,但是已经找不到它的原创了(十分对不起大哭),可以复制建个控制台慢慢调试:

 

  class Program
    { 
        //单例测试
       
           //定义类
        public class MyClass
        {
            public int Property1 { get; set; }
        }
        static void Main()
        {
            MyClass tmp_Class = new MyClass();
            tmp_Class.Property1 = 2;
            Type type = tmp_Class.GetType(); //获取类型
            System.Reflection.PropertyInfo propertyInfo = type.GetProperty("Property1"); //获取指定名称的属性
            int value_Old = (int)propertyInfo.GetValue(tmp_Class, null); //获取属性值
            Console.WriteLine(value_Old);
            propertyInfo.SetValue(tmp_Class, 5, null); //给对应属性赋值
            int value_New = (int)propertyInfo.GetValue(tmp_Class, null);
            Console.WriteLine(value_New);
            // Console.WriteLine();
            Console.ReadLine();


        }
    
    }

 

另外附加点小知识:

1、GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,x.GetType(),其中x为变量名

2、typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称

3、System.Type.GetType(),有两个重载方法

比如有这样一个变量i: 
Int32 i = new Int32(); 

使用GetType(),i.GetType()返回值是Int32的类型,但是无法使用typeof(i),因为i是一个变量,

使用typeof(),则只能:typeof(Int32),返回的同样是Int32的类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值