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. 阿里Java规范:【强制】所有的 POJO 类属性必须使用包装数据类型

    在 Java 开发手册中有这一条: 我们知道基本类型和包装类型有很多不同点: 封装类型可以调用各种方法,而基本类型没有 封装类型声明字段之后可以不设置默认值,而基本类型需要初始化默认值.比如 int ...

  2. 使用 Swoole 加速你的 CMS 系统

    项目介绍 MyCms是一款基于Laravel开发的开源免费的自媒体博客CMS系统,适用于个人网站及企业网站开发使用,助力个人开发者知识技术变现 Swoole介绍 Swoole: PHP的异步.并行.高 ...

  3. MySQL运维开发之路

    MySql h1 { color: rgba(0, 60, 128, 1); text-align: center } h1:hover { color: rgba(0, 255, 111, 1) } ...

  4. python11day

    昨日回顾 函数的参数: 实参角度:位置参数.关键字参数.混合参数 形参角度:位置参数.默认参数.仅限关键字参数.万能参数 形参角度参数顺序:位置参数,*args,默认参数,仅限关键字参数,**kwar ...

  5. 学习MyBatis必知必会(2)~MyBatis基本介绍和MyBatis基本使用

    一.MyBatis框架基本介绍: 1.认识 MyBatis: MyBatis 是支持普通 SQL 查询,存储过程和高级映射的持久层框架,严格上说应该是一个 SQL 映射框架. 其前身是 iBatis, ...

  6. Webpack之 webpack-dev-server 中的 contentBase配置及作用

    contentBase:主要是指定静态资源的根目录的.  

  7. react直接使用bootstrap失效的原因

    react用的是className!而不是class~

  8. windows10下设置Maven的本地仓库和阿里云的远程中央仓库

    感谢原文作者:测试zhang 原文链接:https://www.jianshu.com/p/1782feee6eff 菜鸟:https://www.runoob.com/maven/ 1.设置Mave ...

  9. Android 实用开源库(不定期更新)

    ZXing 极其好用的二维码开源库. GayHub:https://github.com/zxing/zxing MPAndroidChart MPAndroidChart 是 Android 一个强 ...

  10. 前端常见原生方法的实现(bind,promise,new,extends,深拷贝,函数防抖,函数节流)

    前端原生方法的实现,这里写一下常见的一些实现: 1.bind Function.prototype.bind2 = function (context) { var self = this; retu ...