• 反射


       public class Love
        
    {
            
    public int field1;
            
    private string _name;

            
    public Love()
            
    {

            }


            
    public string Name
            
    {
                
    get
                
    {
                    
    return _name;
                }


                
    set
                
    {
                    _name 
    = value;
                }

            }



            
    public int GetInt(int a)
            
    {
                
    return a;
            }




            
    public void Display(string str)
            
    {
                System.Windows.Forms.MessageBox.Show(str);
            }


        }



    测试代码:

    private void test()
            
    {
                Love love 
    = new Love();
                Type type 
    = love.GetType();

                type.InvokeMember(
    "Display", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, love, new object[] "aldfjdlf" });

                
    //调用有返回值的方法
                int i = (int)type.InvokeMember("GetInt", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, love, new object[] 1 });
                MessageBox.Show(i.ToString());

                
    //设置属性值
                type.InvokeMember("Name", BindingFlags.SetProperty, null, love, new string[] "abc" });

                
    //获取属性值
                string str = (string)type.InvokeMember("Name", BindingFlags.GetProperty, null, love, null);
                MessageBox.Show(str);


                
    //设置字段值
                type.InvokeMember("field1", BindingFlags.SetField, null, love, new object[] 444 });

                
    //获取公有字段值
                int f = (int)type.InvokeMember("field1", BindingFlags.GetField, null, love, null);
                MessageBox.Show(f.ToString());

                
    //获取私有字段值
                string name = (string)type.InvokeMember("_name", BindingFlags.GetField | BindingFlags.NonPublic |BindingFlags.Instance, null, love, null);
                MessageBox.Show(name);


            }
  • 相关阅读:
    容器镜像服务联手 IDE 插件,实现一键部署、持续集成与交付
    阿里巴巴大规模神龙裸金属 Kubernetes 集群运维实践
    4 个概念,1 个动作,让应用管理变得更简单
    从零开始入门 | Kubernetes 中的服务发现与负载均衡
    最佳实践 | 数据库迁云解决方案选型 & 流程全解析
    Thumbnail 图片帮助
    验证码-WebVcode
    访问者(Visitor)模式
    享元(Flyweight)模式
    中介者(Mediator)模式
  • 原文地址:https://www.cnblogs.com/gxh973121/p/454784.html
Copyright © 2020-2023  润新知