码迷,mamicode.com
首页 > 其他好文 > 详细

C#自省

时间:2014-08-21 22:28:35      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   strong   数据   

C#自省

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

  bubuko.com,布布扣

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

  bubuko.com,布布扣

bubuko.com,布布扣
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 方法。

  bubuko.com,布布扣

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

  bubuko.com,布布扣

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

  bubuko.com,布布扣

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

  bubuko.com,布布扣

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

bubuko.com,布布扣
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 ("\nReflection.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 ("\n{0}.", MyType.FullName);
        Console.Write ("{0} - ", Myfieldinfo.Name);
        Console.Write ("{0};", Myfieldinfo.GetValue(Myfield));
        Console.Write ("\nFieldType = {0}", Myfieldinfo.FieldType);
    return 0;
    }
}
View Code

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

  bubuko.com,布布扣

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

  

C#自省,布布扣,bubuko.com

C#自省

标签:style   blog   http   color   os   io   strong   数据   

原文地址:http://www.cnblogs.com/tekkaman/p/3928066.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!