C#反射获取属性的实例:

案例一:

以下是实体类:

 class Gneral
    {
        protected string Str { get; set; } = "你好,受保护的变量";

        string Str1 { get; set; } = "你好";

      public   bool Str2 { get; set; } = true;
    }

以下是获取属性的方法:

    /// <summary>
        /// 这是获取公开属性的方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="propertyname"></param>
        /// <returns></returns>
        public static string GetObjectPropertyValue<T>(T t, string propertyname)
        {
            Type type = typeof(T);

            PropertyInfo property = type.GetProperty(propertyname);

            if (property == null) return string.Empty;

            object o = property.GetValue(t, null);

            if (o == null) return string.Empty;
            return o.ToString();
        }

以下是使用的案例:

class Program
    {
        static Gneral gneral = new Gneral();
        static void Main(string[] args)
        {


            result = GetObjectPropertyValue(gneral, "Str");
            Console.WriteLine(result);

            result = GetObjectPropertyValue(gneral, "Str1");
            Console.WriteLine(result);

            result =GetObjectPropertyValue(gneral, "Str2");
            Console.WriteLine(result);

            Console.WriteLine("*********************************************");

            var hProperties = typeof(Gneral).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);//获取非公开属性
  foreach (var item in hProperties)
            {
                if (item.Name== "Str")
                {
                    Console.WriteLine(item.GetValue(gneral));//获取反射后各属性的值
                }
               
            }

            Console.ReadLine();
        }

 显示的结果:

案例二:

以下是抽象父类:

abstract class BaseClass
    {

        protected bool Isruning { get; set; } = false;
    }

 以下是继承的子类:

class TestRefletion : BaseClass//继承上面的父类
    {
        public static  TestRefletion Cur = new TestRefletion();//单例模式

        protected bool Isrun = true;  
        private TestRefletion()
        {
            test();
        }
        void test()
        {
            if (!Isruning)
            {
                Isruning = true ;
            }
        }
    }

 

以下是使用:

写在方法中就行。

TestRefletion testRefletion = TestRefletion.Cur;

            var hProperties1 = typeof(TestRefletion).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);//获取非公开属性

            foreach (var item in hProperties1)
            {
                if (item.Name == "Isruning")//判断是否是我要的那个属性
                {
                    Console.WriteLine(item.GetValue(testRefletion));//获取反射后各属性的值
                }

            }

 展示结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值