zoukankan      html  css  js  c++  java
  • C#自省

    C#自省

    1、根据string,获取type。Type.GetType 方法,获取具有指定名称的 Type,执行区分大小写的搜索。

      

    2、根据obj,获取type。Object.GetType 方法,获取当前实例的 Type

      

    int n1 = 12;
    int n2 = 82;
    long n3 = 12;
    
    Console.WriteLine("n1 and n2 are the same type: {0}",
                      Object.ReferenceEquals(n1.GetType(), n2.GetType()));
    Console.WriteLine("n1 and n3 are the same type: {0}",
                      Object.ReferenceEquals(n1.GetType(), n3.GetType()));
    // The example displays the following output:
    //       n1 and n2 are the same type: True
    //       n1 and n3 are the same type: False      
    View Code

    3、根据type,创建obj。Activator.CreateInstance 方法。

      

    4、根据type,获取所有public 成员变量。Type.GetField 方法。

      

    5、根据FieldInfo与string,设置obj的成员变量。FieldInfo.SetValue 方法。

      

    6、根据obj,获取期成员变量类型。FieldInfo.FieldType 属性。

      

      结果为某个基元数据类型,如 String、Boolean 或 GUID。若要获取 FieldType 属性,请先获取 Type 类。 从 Type 获取 FieldInfo。 从 FieldInfo 获取 FieldType 值。

    using System;
    using System.Reflection;
    
    
    // Make a field.
    public class Myfield
    {
        private string field = "private field";
    }
    
    public class Myfieldinfo
    {
        public static int Main()
        {
            Console.WriteLine ("
    Reflection.FieldInfo");
            Myfield Myfield = new Myfield();
    
            // Get the type and FieldInfo.
            Type MyType = typeof(Myfield);
            FieldInfo Myfieldinfo = MyType.GetField("field", 
                BindingFlags.Instance|BindingFlags.NonPublic);
    
            // Get and display the FieldType.
            Console.Write ("
    {0}.", MyType.FullName);
            Console.Write ("{0} - ", Myfieldinfo.Name);
            Console.Write ("{0};", Myfieldinfo.GetValue(Myfield));
            Console.Write ("
    FieldType = {0}", Myfieldinfo.FieldType);
        return 0;
        }
    }
    View Code

    7、获取所继承的接口。Type.GetInterfaces 方法。

      

    参考:http://msdn.microsoft.com/zh-cn/library/6z33zd7h(v=vs.110).aspx

      

  • 相关阅读:
    centos7网络配置
    centos7安装gitlab错误解决
    数据库事务的隔离级别
    数据库事务的特性
    windows系统下安装redis扩展
    windows 7搭建基于docker的nginx, php运行环境
    php foreach 引用注意
    mysql远程连接10038
    mysql忘记root密码
    phpstorm添加sdk
  • 原文地址:https://www.cnblogs.com/tekkaman/p/3928066.html
Copyright © 2011-2022 走看看