C#自省

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

  C#自省-LMLPHP

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

  C#自省-LMLPHP

int n1 = ;
int n2 = ;
long n3 = ; 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

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

  C#自省-LMLPHP

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

  C#自省-LMLPHP

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

  C#自省-LMLPHP

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

  C#自省-LMLPHP

  结果为某个基元数据类型,如 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 ("\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 ;
}
}

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

  C#自省-LMLPHP

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

  

05-28 16:15