`
guoyiqi
  • 浏览: 961873 次
社区版块
存档分类
最新评论

使用反射检查和实例化泛型类型(转自:http://www.csharpwin.com/csharpspace/12241r3312.shtml)

 
阅读更多

与其他类型的信息一样,泛型类型的信息的获取方式为:检查表示泛型类型的Type对象。主要的差异在于,泛型类型具有一组表示其泛型类型参数的Type对象。本部分的第一个步骤是检查泛型类型。

通过将类型变量绑定到泛型类型定义的类型参数,可以创建表示构造类型的Type对象。第二个步骤演示此过程。

检查泛型类型及其类型参数

  1. 获取表示泛型类型的Type实例。在下面的代码中,使用 C# 的typeof运算符(在 Visual Basic 中为GetType,在 Visual C++ 中为typeid)获取类型。有关获取Type对象的其他方法,请参见Type类主题。注意,余下的步骤中,类型包含在名为t的方法参数中。

    C#

    Type d1 =typeof(Dictionary<,>);

  2. 使用IsGenericType属性确定类型是否为泛型,然后使用IsGenericTypeDefinition属性确定类型是否为泛型类型定义。

    C#

    Console.WriteLine(" Is this a generic type? {0}",
    t.IsGenericType);
    Console.WriteLine(" Is this a generic type definition? {0}",
    t.IsGenericTypeDefinition);

  3. 使用GetGenericArguments方法获取包含泛型类型参数的数组。

    C#

    Type[] typeParameters = t.GetGenericArguments();

  4. 对每个类型变量,使用IsGenericParameter属性确定其是不是类型参数(例如,在泛型类型定义中),是不是已为类型参数指定的类型(例如,在构造类型中)。

    C#

    Console.WriteLine(" List {0} type arguments:",
    typeParameters.Length);
    foreach( Type tParamintypeParameters )
    {
    if(tParam.IsGenericParameter)
    {
    DisplayGenericParameter(tParam);
    }
    else
    {
    Console.WriteLine(" Type argument: {0}",
    tParam);
    }
    }

  5. 在类型系统中,和普通类型一样,泛型类型参数是由Type的实例表示的。下面的代码演示表示泛型类型参数的Type对象的名称和参数位置。此处,参数位置无足轻重;它在检查类型参数(用作其他泛型类型的类型变量)时更有价值。

    C#

    private
    staticvoidDisplayGenericParameter(Type tp)
    {
    Console.WriteLine(" Type parameter: {0} position {1}",
    tp.Name, tp.GenericParameterPosition);

  6. 通过使用GetGenericParameterConstraints方法获取单个数组中的所有约束,确定泛型类型参数的基类型约束和接口约束。不保证约束处于任何特定顺序。

    C#

    Type classConstraint =null;

    foreach(Type iConstraintintp.GetGenericParameterConstraints())
    {
    if(iConstraint.IsInterface)
    {
    Console.WriteLine(" Interface constraint: {0}",
    iConstraint);
    }
    }

    if(classConstraint !=null)
    {
    Console.WriteLine(" Base type constraint: {0}",
    tp.BaseType);
    }
    else
    Console.WriteLine(" Base type constraint: None");

  7. 使用GenericParameterAttributes属性获取类型参数的特殊约束,如要求其为引用类型。该属性还包含表示方差的值,该值可屏蔽,如下面的代码所示。

    C#

    GenericParameterAttributes sConstraints =
    tp.GenericParameterAttributes &
    GenericParameterAttributes.SpecialConstraintMask;

  8. 特殊约束的属性为标志,表示没有任何特殊约束的标志 (System.Reflection.GenericParameterAttributes.None) 还表示没有协变或逆变。因此,若要测试其中一个条件,必须使用适当的屏蔽。在此情况下,请使用System.Reflection.GenericParameterAttributes.SpecialConstraintMask隔离特殊约束标志。

    C#

    if
    (sConstraints == GenericParameterAttributes.None)
    {
    Console.WriteLine(" No special constraints.");
    }
    else
    {
    if(GenericParameterAttributes.None != (sConstraints &
    GenericParameterAttributes.DefaultConstructorConstraint))
    {
    Console.WriteLine(" Must have a parameterless constructor.");
    }
    if(GenericParameterAttributes.None != (sConstraints &
    GenericParameterAttributes.ReferenceTypeConstraint))
    {
    Console.WriteLine(" Must be a reference type.");
    }
    if(GenericParameterAttributes.None != (sConstraints &
    GenericParameterAttributes.NotNullableValueTypeConstraint))
    {
    Console.WriteLine(" Must be a non-nullable value type.");
    }
    }

构造泛型类型的实例

泛型类型和模板类似。除非指定其泛型类型参数的实际类型,否则不能创建泛型类型的实例。若要在运行时使用反射创建实例,需要使用MakeGenericType方法。

构造泛型类型的实例

  1. 获取表示泛型类型的Type对象。下面的代码以两种不同方式获取泛型类型Dictionary:一种方法使用System.Type.GetType(System.String)方法重载和描述类型的字符串,另一种方法调用构造类型Dictionary<String, Example>(在 Visual Basic 中为Dictionary(Of String, Example))的GetGenericTypeDefinition方法。MakeGenericType方法需要泛型类型定义。

    C#

    // Use the typeof operator to create the generic type

    // definition directly. To specify the generic type definition,
    // omit the type arguments but retain the comma that separates
    // them.
    Type d1 =typeof(Dictionary<,>);

    // You can also obtain the generic type definition from a
    // constructed class. In this case, the constructed class
    // is a dictionary of Example objects, with String keys.
    Dictionary<string, Example> d2 =newDictionary<string, Example>();
    // Get a Type object that represents the constructed type,
    // and from that get the generic type definition. The
    // variables d1 and d4 contain the same type.
    Type d3 = d2.GetType();
    Type d4 = d3.GetGenericTypeDefinition();

  2. 构造一组用于替换类型参数的类型变量。数组必须包含正确数目的Type对象,并且顺序和对象在类型参数列表中的顺序相同。在这种情况下,键(第一个类型参数)的类型为String,字典中的值是名为Example的类的实例。

    C#
    Type[] typeArgs = {typeof(string),typeof(Example)};

  3. 调用MakeGenericType方法将类型变量绑定到类型参数,然后构造类型。

    C#
    Type constructed = d1.MakeGenericType(typeArgs);

  4. 使用CreateInstance方法重载来创建构造类型的对象。下面的代码在生成的Dictionary<String, Example>对象中存储Example类的两个实例。

    C#

    object
    o = Activator.CreateInstance(constructed);

示例

下面的代码示例定义DisplayGenericType方法来检查泛型类型定义和代码中使用的构造类型,并显示它们的信息。DisplayGenericType方法演示如何使用IsGenericTypeIsGenericParameterGenericParameterPosition属性以及GetGenericArguments方法。

该示例还定义DisplayGenericParameter方法来检查泛型类型参数并显示其约束。

代码示例定义一组测试类型,包括说明类型参数约束的泛型类型,并演示如何显示这些类型的信息。

示例通过创建一组类型参数并调用MakeGenericType方法,从Dictionary类构造类型。程序对使用MakeGenericType构造的Type对象和使用typeof(Visual Basic 中为GetType)获取的Type对象进行比较,演示这两个对象是相同的。类似地,程序使用GetGenericTypeDefinition方法获取构造类型的泛型类型定义,并将其与表示Dictionary类的Type对象进行比较。

C#
usingSystem;
usingSystem.Reflection;
usingSystem.Collections.Generic;
usingSystem.Security.Permissions;

// Define an example interface.
publicinterfaceITestArgument {}

// Define an example base class.
publicclassTestBase {}

// Define a generic class with one parameter. The parameter
// has three constraints: It must inherit TestBase, it must
// implement ITestArgument, and it must have a parameterless
// constructor.
publicclassTest<T>whereT : TestBase, ITestArgument,new() {}

// Define a class that meets the constraints on the type
// parameter of class Test.
publicclassTestArgument : TestBase, ITestArgument
{
publicTestArgument() {}
}

publicclassExample
{
// The following method displays information about a generic
// type.
privatestaticvoidDisplayGenericType(Type t)
{
Console.WriteLine("/r/n {0}", t);
Console.WriteLine(" Is this a generic type? {0}",
t.IsGenericType);
Console.WriteLine(" Is this a generic type definition? {0}",
t.IsGenericTypeDefinition);

// Get the generic type parameters or type arguments.
Type[] typeParameters = t.GetGenericArguments();

Console.WriteLine(" List {0} type arguments:",
typeParameters.Length);
foreach( Type tParamintypeParameters )
{
if(tParam.IsGenericParameter)
{
DisplayGenericParameter(tParam);
}
else
{
Console.WriteLine(" Type argument: {0}",
tParam);
}
}
}

// The following method displays information about a generic
// type parameter. Generic type parameters are represented by
// instances of System.Type, just like ordinary types.
privatestaticvoidDisplayGenericParameter(Type tp)
{
Console.WriteLine(" Type parameter: {0} position {1}",
tp.Name, tp.GenericParameterPosition);

Type classConstraint =null;

foreach(Type iConstraintintp.GetGenericParameterConstraints())
{
if(iConstraint.IsInterface)
{
Console.WriteLine(" Interface constraint: {0}",
iConstraint);
}
}

if(classConstraint !=null)
{
Console.WriteLine(" Base type constraint: {0}",
tp.BaseType);
}
else
Console.WriteLine(" Base type constraint: None");

GenericParameterAttributes sConstraints =
tp.GenericParameterAttributes &
GenericParameterAttributes.SpecialConstraintMask;

if(sConstraints == GenericParameterAttributes.None)
{
Console.WriteLine(" No special constraints.");
}
else
{
if(GenericParameterAttributes.None != (sConstraints &
GenericParameterAttributes.DefaultConstructorConstraint))
{
Console.WriteLine(" Must have a parameterless constructor.");
}
if(GenericParameterAttributes.None != (sConstraints &
GenericParameterAttributes.ReferenceTypeConstraint))
{
Console.WriteLine(" Must be a reference type.");
}
if(GenericParameterAttributes.None != (sConstraints &
GenericParameterAttributes.NotNullableValueTypeConstraint))
{
Console.WriteLine(" Must be a non-nullable value type.");
}
}
}

[PermissionSetAttribute(SecurityAction.Demand, Name="FullTrust")]
publicstaticvoidMain()
{
// Two ways to get a Type object that represents the generic
// type definition of the Dictionary class.
//
// Use the typeof operator to create the generic type
// definition directly. To specify the generic type definition,
// omit the type arguments but retain the comma that separates
// them.
Type d1 =typeof(Dictionary<,>);

// You can also obtain the generic type definition from a
// constructed class. In this case, the constructed class
// is a dictionary of Example objects, with String keys.
Dictionary<string, Example> d2 =newDictionary<string, Example>();
// Get a Type object that represents the constructed type,
// and from that get the generic type definition. The
// variables d1 and d4 contain the same type.
Type d3 = d2.GetType();
Type d4 = d3.GetGenericTypeDefinition();

// Display information for the generic type definition, and
// for the constructed type Dictionary<String, Example>.
DisplayGenericType(d1);
DisplayGenericType(d2.GetType());

// Construct an array of type arguments to substitute for
// the type parameters of the generic Dictionary class.
// The array must contain the correct number of types, in
// the same order that they appear in the type parameter
// list of Dictionary. The key (first type parameter)
// is of type string, and the type to be contained in the
// dictionary is Example.
Type[] typeArgs = {typeof(string),typeof(Example)};

// Construct the type Dictionary<String, Example>.
Type constructed = d1.MakeGenericType(typeArgs);

DisplayGenericType(constructed);

objecto = Activator.CreateInstance(constructed);

Console.WriteLine("/r/nCompare types obtained by different methods:");
Console.WriteLine(" Are the constructed types equal? {0}",
(d2.GetType()==constructed));
Console.WriteLine(" Are the generic definitions equal? {0}",
(d1==constructed.GetGenericTypeDefinition()));

// Demonstrate the DisplayGenericType and
// DisplayGenericParameter methods with the Test class
// defined above. This shows base, interface, and special
// constraints.
DisplayGenericType(typeof(Test<>));
}
}

分享到:
评论

相关推荐

    https://raw.githubusercontent.com/selva86/datasets/master/a10.csv

    https://raw.githubusercontent.com/selva86/datasets/master/a10.csv,时间序列分析基本方法和实例相关数据

    shell实例手册

    # python实例手册下载地址: http://hi.baidu.com/quanzhou722/item/cf4471f8e23d3149932af2a7 # LazyManage系统批量管理软件下载[shell]: http://hi.baidu.com/quanzhou722/item/4ccf7e88a877eaccef083d1a # ...

    jQuery弹出层插件大全

    目前用的比较多的,最新版本是thickbox3.1 下载地址:http://jquery.com/demo/thickbox/#examples 2.colorBox 官方网站:http://colorpowered.com/colorbox/ ...演示实例:http://www.shadowbox-js.com/index.html

    jsp2.0 应用教程 光盘

    (1)本书和随书附送的光盘中涉及的文档、软件、图片和代码等项目仅供教学使用。 (2)本书实例源程序运行测试环境为: JDK 5.0 update 6和JDK 6.0 beta Tomcat 5.5.12 MySQL 5.0.16 (3)本书涉及的共享软件或免费软件...

    esp8266从入门到精通的实例,网上购买

    玩转ESP8266 SDK编程【实例】, 第1集(公开):套件介绍 观看地址:http://v.youku.com/v_show/id_XMTUzNzM3ODg3Mg==.html 操作演示:http://pan.baidu.com/s/1dEGjwVv(视频演示全家福) 第2集(加密):组装WIFI...

    TEM011 - AxureUX中后台管理信息系统通用原型方案,跟其他的不同哦

    实例 模板 TEM011 - AxureUX中后台管理信息系统通用原型方案,跟其他的不同哦 演示地址:http://www.axureux.com/home/Templates011.html TEM011 - AxureUX中后台管理信息系统通用原型方案,跟其他的不同哦 演示地址...

    3.java实例化泛型类.zip

    3.java实例化泛型类.zip3.java实例化泛型类.zip3.java实例化泛型类.zip3.java实例化泛型类.zip3.java实例化泛型类.zip3.java实例化泛型类.zip3.java实例化泛型类.zip3.java实例化泛型类.zip3.java实例化泛型类.zip3....

    iquery经典教程

    所有效果说明:基本的鼠标互动:拖拽(drag and dropping)、排序... CSS文件:http://dev.jquery.com/view/trunk/themes/flora/flora.all.css 选项说明:http://docs.jquery.com/UI/Tabs/tabs#initialoptions 选项实例:...

    jqert ui demo

    所有效果说明: 基本的鼠标互动: 拖拽(drag and dropping)、排序(sorting)、选择(selecting)、缩放(resizing) 各种互动效果: ...实例http://dev.jquery.com/view/trunk/plugins/ui/demos/ui.magnifier.html

    jQuery-ui Demo 官方UI插件

    最新官方jQuery UI插件 主流特效Demo,绝不含糊。 好东西不需要过多的言辞修饰,下了就知道! 所有效果说明: 基本的鼠标互动: ...实例http://dev.jquery.com/view/trunk/plugins/ui/demos/ui.magnifier.html

    UploadiFive文件上传插件v1.2.2-standard,基于HMTL5和jQuery,前身Uploadify,支持拖拽手机和手机上传

    UploadiFive是一款来自国外的、优秀的jQuery插件,主要...应用实例:http://w3croom.com/read.php?tid-4402.html 前身介绍:http://www.d1php.info/uploadifydoc/ http://baike.baidu.com/view/5915599.htm?fr=aladdin

    Asp.net 调用淘宝客Top Api 接口 实例源码!

    //请去http://www.alimama.com 阿里妈妈网站得到一个pid帐号 如:mm_10594045_0_0 //没有App Key与App Secret 与mm_10594045_0_0 网站数据是没办法读取出来,以下的帐号我是随便填一个上去为了测试用的,数据是不显示...

    hge开发必备之开发包和实例

    OGRE, http://www.ogre3d.org/ 如果研究3D,不研究他,实在没道理 Irrlicht,http://irrlicht.sourceforge.net/ 虽然我将他定义为入门级的3D引擎,但功能很强大。 KlayGE,http://klayge.sourceforge.net/ 这是国人写...

    基于Lodop打印php网页小票打印实例

    php网页小票打印实例,打印机安装设置完成后,然后下载【Lodop打印插件】,安装插件即可 演示地址:http://www.phprr.com/demo-2127

    uploadifive-v1.1.2-standard

    UploadiFive是一款来自国外的、优秀的jQuery插件,主要...应用实例:http://w3croom.com/read.php?tid-4402.html 前身介绍:http://www.d1php.info/uploadifydoc/ http://baike.baidu.com/view/5915599.htm?fr=aladdin

    Java语言程序设计 进阶 10th

    《Java语言程序设计进阶篇》(原书第5版)的主要特点:基础篇介绍基础内容,进阶篇介绍高级内容,教师能够按需选择理想的教材。包括面向对象程序设计的深入论述,包含GUI程序设计的基础和扩展实例。提供大量实例,实例...

    ant 版本制作实例_uniportal 和ant配置应用实例

    NULL 博文链接:https://ladybird2010.iteye.com/blog/753577

    Web 技术教程w3school离线完整版(含HTML5)

    Web 技术教程 网址:htt://pwww.w3school.com.cn 讲解、实例与编辑运行测试。

Global site tag (gtag.js) - Google Analytics