zoukankan      html  css  js  c++  java
  • c# 反射小Demo

    今天看了一下C#的反射,之前一直感觉反射是一种很高大上的东东,现在才发现不过是纸老虎而以.

    所谓的反射就是,只是知道一个它是一个对象不知道其中有什么字段方法属性等,而反射就是用来获取一个未知对象的字段方法事件等.

    下面是从网上看到的一个小例子,

        class Person
        {
            private string _Name;
            private int _Age;
            private string _Sex;
    
            public string Name
            {
                get { return this._Name; }
                set { this._Name = value; }
            }
    
            public int Age
            {
                get { return this._Age; }
                set { this._Age = value; }
            }
    
            public string Sex
            {
                get { return this._Sex; }
                set { this._Sex = value; }
            }
        }

    上面写的是需要操作的类,下面是进行实地操作

     class Program
        {
            static void Main(string[] args)
            {
                Person person = new Person();
                person.Name = "snoopy";
                person.Age = 5;
                person.Sex = "male";
    
                //
                PropertyInfo[] infos = person.GetType().GetProperties();
                //获取属性 (只限字段)
                foreach (PropertyInfo info in infos)
                {
                    
                    Console.WriteLine("属性的类型是" + info.PropertyType + "属性的名称是" + info.Name + ":" +  "属性的数值是" + info.GetValue(person, null));
                }
    
    
    
                Console.WriteLine("设置Person.Name = Hellokitty");
                //设置属性
                foreach (PropertyInfo info in infos)
                {
                    if (info.Name == "Name")
                    {
                        info.SetValue(person, "Hellokitty", null);
                    }
                }
            }
        }
  • 相关阅读:
    Python合集之文件操作(二)
    Python合集之文件操作(一)
    Python合集之异常(二)
    Python合集之异常(一)
    Python合集之模块(五)
    Visual Studio 配置额外工具 Windows Terminal 等
    CMakeList.txt
    alpha智能图像(全栈的进阶之路)
    位运算实现多状态控制
    缓存函数 memorize
  • 原文地址:https://www.cnblogs.com/mawanli/p/7081183.html
Copyright © 2011-2022 走看看