【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
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 ("\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; } }
7、获取所继承的接口。Type.GetInterfaces 方法。
参考:http://msdn.microsoft.com/zh-cn/library/6z33zd7h(v=vs.110).aspx
时间: 2024-10-13 16:09:45