Type属性的应用

Type type = typeof(MyClass);
Console.Write("$类型名:{ type.Name}");
Console.Write("$类全名:{type.FullName}" );
Console.Write("$命名空间名:{ype.Namespace}");
Console.Write("$程序集名:{type.Assembly}" );
Console.Write("$模块名:{type.Module}" );
Console.Write("$基类名:{type.BaseType}" ); //C# 中,一个类型只能继承一个类型(基类型),使用实例的 Type.BaseType 属性,可以获取到此类型的基类型。
Console.Write("$是否类:{type.IsClass}");
Console.Write("$类的公共成员:{}");
MemberInfo[] memberInfos = type.GetMembers();//得到所有公共成员
foreach (var item in memberInfos)
{
Console.Write(string.Format("${ item.MemberType}:{ item}")); }

Type.MakeGenericType 动态创建泛型

// 先创建开放泛型
Type openType = typeof(List<>);
// 再创建具象泛型
Type target = openType.MakeGenericType(new[] { typeof(string) });
// 最后创建泛型实例
List<string> result = (List<string>)Activator.CreateInstance(target);

c# Type.InvokeMember用法

public object InvokeMember(string, BindingFlags, Binder, object, object[]);
string:你所要调用的函数名

BindingFlags:你所要调用的函数的属性,可以组合

Binder:实例
object:调用该成员函数的实例

object[]:参数,

下面是msdn例子:

 class MyType
{
Int32 myField;
public MyType(ref Int32 x) { x *= 5; }
public override String ToString() { return myField.ToString(); }
public Int32 MyProp
{
get { return myField; }
set
{
if (value < 1)
throw new ArgumentOutOfRangeException("value", value, "value must be > 0");
myField = value;
}
}
} class MyApp
{
static void Main()
{
Type t = typeof(MyType);
// Create an instance of a type.
Object[] args = new Object[] { 8 };
int ss = 5;
Console.WriteLine("The value of x before the constructor is called is {0}.", args[0]);
Object obj =(object) new MyType(ref ss);
//也可以这样写 Object obj =t.InvokeMember(null,BindingFlags.CreateInstance, null, null, args);
Console.WriteLine("Type: " + obj.GetType().ToString());
Console.WriteLine("The value of x after the constructor returns is {0}.", args[0]); // Read and write to a field.
t.InvokeMember("myField",BindingFlags.Instance|BindingFlags.NonPublic| BindingFlags.SetField, null, obj, new Object[] { 5 });
Int32 v = (Int32)t.InvokeMember("myField",BindingFlags.NonPublic |BindingFlags.Instance | BindingFlags.GetField, null, obj, null);
Console.WriteLine("myField: " + v); // Call a method.
String s = (String)t.InvokeMember("ToString",BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, obj, null);
Console.WriteLine("ToString: " + s); // Read and write a property. First, attempt to assign an
// invalid value; then assign a valid value; finally, get
// the value.
try
{
// Assign the value zero to MyProp. The Property Set
// throws an exception, because zero is an invalid value.
// InvokeMember catches the exception, and throws
// TargetInvocationException. To discover the real cause
// you must catch TargetInvocationException and examine
// the inner exception.
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { 0 });
}
catch (TargetInvocationException e)
{
// If the property assignment failed for some unexpected
// reason, rethrow the TargetInvocationException.
if (e.InnerException.GetType() != typeof(ArgumentOutOfRangeException))
throw;
Console.WriteLine("An invalid value was assigned to MyProp.");
}
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] { 2 });
v = (Int32)t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, obj, null);
Console.WriteLine("MyProp: " + v);
}
}

Type类 GETXXXX的方法

GetConstructor(), GetConstructors():返回ConstructorInfo类型,用于取得该类的构造函数的信息

GetEvent(), GetEvents():返回EventInfo类型,用于取得该类的事件的信息

GetField(), GetFields():返回FieldInfo类型,用于取得该类的字段(成员变量)的信息

GetInterface(), GetInterfaces():返回InterfaceInfo类型,用于取得该类实现的接口的信息

GetMember(), GetMembers():返回MemberInfo类型,用于取得该类的所有成员的信息

GetMethod(), GetMethods():返回MethodInfo类型,用于取得该类的方法的信息
 
GetProperty(), GetProperties():返回PropertyInfo类型,用于取得该类的属性的信息
    可以调用这些成员,其方式是调用Type的InvokeMember()方法,或者调用MethodInfo, PropertyInfo和其他类的Invoke()方法。

。。。。。。。

4、使用示例代码

1) 查看类中的构造方法

  NewClassw nc = new NewClassw();
Type t = nc.GetType();
ConstructorInfo[] ci = t.GetConstructors(); //获取类的所有构造函数
foreach (ConstructorInfo c in ci) //遍历每一个构造函数
{
ParameterInfo[] ps = c.GetParameters(); //取出每个构造函数的所有参数

foreach (ParameterInfo pi in ps) //遍历并打印所该构造函数的所有参数
{
Console.Write(pi.ParameterType.ToString() + " " + pi.Name + ",");
}
Console.WriteLine();
}

2) 用构造函数动态创建对象

Type t = typeof(NewClassw);

Type[] pt = new Type[2];

pt[0] = typeof(string);

pt[1] = typeof(string);
 //根据参数类型获取构造函数 

ConstructorInfo ci = t.GetConstructor(pt); 
 //构造Object数组,作为构造函数的输入参数 

object[] obj = new object[2]{"grayworm","hi.baidu.com/grayworm"}; 
 //调用构造函数生成对象 

object o = ci.Invoke(obj); 

//调用生成的对象的方法测试是否对象生成成功 

//((NewClassw)o).show();

3) 用Activator创建对象

Type t = typeof(NewClassw);

//构造函数的参数 

object[] obj = new object[2] { "grayworm", "hi.baidu.com/grayworm" }; 

//用Activator的CreateInstance静态方法,生成新对象 
 object o = Activator.CreateInstance(t,"grayworm","hi.baidu.com/grayworm"); 

//((NewClassw)o).show();

4) 查看类中的属性

NewClassw nc = new NewClassw();

Type t = nc.GetType();

PropertyInfo[] pis = t.GetProperties();

foreach(PropertyInfo pi in pis)

{

Console.WriteLine(pi.Name);

}

5) 查看类中的public方法

NewClassw nc = new NewClassw();

Type t = nc.GetType();

MethodInfo[] mis = t.GetMethods();

foreach (MethodInfo mi in mis)

{

Console.WriteLine(mi.ReturnType+" "+mi.Name);

}

6) 查看类中的public字段

NewClassw nc = new NewClassw();

Type t = nc.GetType();

FieldInfo[] fis = t.GetFields();

foreach (FieldInfo fi in fis)

{

Console.WriteLine(fi.Name);

}

7) 用反射生成对象,并调用属性、方法和字段进行操作

NewClassw nc = new NewClassw();

Type t = nc.GetType();

object obj = Activator.CreateInstance(t);

//取得ID字段 

FieldInfo fi = t.GetField("ID");

//给ID字段赋值 

fi.SetValue(obj, "k001");

//取得MyName属性 

PropertyInfo pi1 = t.GetProperty("MyName");

//给MyName属性赋值 

pi1.SetValue(obj, "grayworm", null);
 // null表示无参属性,有参是索引,必须传入一个实例,
PropertyInfo pi2 = t.GetProperty("MyInfo");

pi2.SetValue(obj, "hi.baidu.com/grayworm", null);

//取得show方法 

MethodInfo mi = t.GetMethod("show");

//调用show方法 

mi.Invoke(obj, null);


System.Type 创建实例

使用Type.InvokerMember可以调用类型的方法、属性。自然也可以通过调用类型的构造函数来创建一个类型的实例。

//直接调用无参构造函数
Object obj = typeof(Employee).InvokeMember(null, BindingFlags.CreateInstance, null, null, null);//BindingFlags.CreateInstance会调用构造函数
Employee employee =obj as Employee;
employee.Say("InvokeMember default ctor"); // 使用带参数的构造函数
obj = typeof(Employee).InvokeMember(null, BindingFlags.CreateInstance, null, null, new object[] { "david" });
employee = obj as Employee;
((Employee)obj).Say("InvokeMember ctor with argument");

【C#反射】Type的用法的更多相关文章

  1. Activator.CreateInstance 方法 (Type) 的用法

    转自:http://www.cnblogs.com/lmfeng/archive/2012/01/30/2331666.html Activator.CreateInstance 方法 (Type) ...

  2. Java反射的常见用法

    反射的常见用法有三类,第一类是“查看”,比如输入某个类的属性方法等信息,第二类是“装载“,比如装载指定的类到内存里,第三类是“调用”,比如通过传入参数,调用指定的方法. 1 查看属性的修饰符.类型和名 ...

  3. 反射 type 的基本用法,动态加载插件

    这里介绍反射的简单实用 MyClass类 public class MyClass { public int Age { get; set; } public string Name { get; s ...

  4. .Net反射-Type类型扩展

    /// <summary> /// Type 拓展 /// </summary> public static class TypeExtensions { /// <su ...

  5. 反射的一些用法(WP8.1下)

    我初步的理解:反射就是动态调用(dll)类. 比如某个dll有一个类,通过反射就可以知道它里面属性.方法,就可以实现调用. 确实,dll可以直接引用,但是如果遇到这种情况: 添加.删除功能同属一个Dl ...

  6. 详解反射->Type.System

    反射先了解 一:system.Type 获取基本信息: Type.Name   //类名 Type.FullName //完整路径 Type.Namespace //空间名 public class ...

  7. C# 反射的简单用法

    新建两个项目:类库(Model)和控制台应用程序(ReflectTest). 在[Model]中添加一个类[User]: namespace Model { public class User { p ...

  8. java 反射与常用用法

    java通常是先有类再有对象,有对象我就可以调用方法或者属性. 反射其实是通过Class对象来调用类里面的方法.通过反射可以调用私有方法和私有属性.大部分框架都是运用反射原理. 如何获得Class对象 ...

  9. C# 反射 Type.GetType()

    对于外部调用的动态库应用反射时要用到Assembly.LoadFile(),然后才是获取类型.执行方法等;当用反射创建当前程序集中对象实例或执行某个类下静态方法时只需通过Type.GetType(&q ...

随机推荐

  1. 集合框架-工具类-JDK5.0特性-静态导入

    1 package cn.itcast.p4.news.demo; 2 3 import java.util.ArrayList; 4 //import java.util.Collections; ...

  2. linux面试题(重点)

    1.No space left on device ,但df -h,磁盘空间还很富余?原因是 Inode 耗尽.可以使用df -i检查.磁盘中中产生了很多小的临时文件,造成在磁盘空间耗尽之前文件系统的 ...

  3. python3 requests的content和text方法

    text返回的是Unicode型的数据 content返回的是是二进制的数据. 也就是说,如果你想取文本,可以通过r.text. 如果想取图片,文件,则可以通过r.content >>&g ...

  4. linux下查看开放的端口

    Nmap是一款针对大型网络的端口扫描工具,它也适用于单机扫描,它支持很多扫描,也同时支持性能和可靠性统计. [root@localhost ~]# yum install namp [root@loc ...

  5. 不难懂——th: 的常用标签

    关键字>       功能介绍    >      案例 th:id 替换id <input th:id="'xxx' + ${collect.id}"/> ...

  6. python26day

    内容回顾 多态: ​ 一个类表现出的多种形态,实际上是通过继承来完成的 今日内容 super,调用父类的同名方法 按照mro顺序来寻找当前类的下一个类 封装 广义上的封装 方法属性名字前加了__,就变 ...

  7. Vue2和Vue3技术整理1 - 入门篇 - 更新完毕

    Vue2 0.前言 首先说明:要直接上手简单得很,看官网熟悉大概有哪些东西.怎么用的,然后简单练一下就可以做出程序来了,最多两天,无论Vue2还是Vue3,就都完全可以了,Vue3就是比Vue2多了一 ...

  8. 实用的linux 命令

    1. 查看当前文件夹下文件或文件夹所占磁盘的大小 du -sh *|sort -rh 2. 查找某个进程号,脚本或程序所在目录的方法 ll /proc/进程id 3. awk 的用法 (1)累加: a ...

  9. 利用application在页面中显示访问次数

    在jsp页面中实现. <%@ page language="java" contentType="text/html; charset=UTF-8" pa ...

  10. 深入解析HashMap、HashTable (转)

    集合类之番外篇:深入解析HashMap.HashTable Java集合类是个非常重要的知识点,HashMap.HashTable.ConcurrentHashMap等算是集合类中的重点,可谓&quo ...