`
cdragon
  • 浏览: 78309 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

关于“反射”的实现

阅读更多

在C#中,反射对于单个对象实现了类环境中的层次检索;对于相关的多个类间(class groups)实现了运行时的动态调用与创建。后者,更多地用于抽象工厂类的对象创建环境中。

 

基本知识:

用到System.Reflection、System.Activator或System.Object类;

 

1.读取

(1)单个对象,使用System.Object的GetType方法,即可。

using System;
using System.Reflection;

class TypeObjectFromInstanceApp
{
    public static void Main(string[] args)
    {
        int i = 6;
        Type type = i.GetType();
        Console.WriteLine(type.Name);
    }
}

 

(2)或,使用System.Type的GetType方法,

   public static Type GetType(string name);
   public static Type GetType(string name, bool throw);
   public static Type GetType(string name, bool throw,bool ignoreCase);

 

 

using System;
using System.Reflection;

class TypeObjectFromNameApp
{
    public static void DisplaySyntax()
    {
        Console.WriteLine("\nSyntax: TypeObjectFromName " +
            "<typename>\n");
    }

    public static void DisplayTypeInfo(string typename)
    {
        try
        {
            Type type = Type.GetType(typename, true);
            Console.WriteLine("\n'{0}' is located in the " +
                "module {1}", typename, type.Module);
        }
        catch(TypeLoadException e)
        {
            Console.WriteLine("\n'{0}' could not be " +
                "located. Did you qualify with a namespace?",
                typename);
        }
    }

    public static void Main(string[] args)
    {
        if (1 != args.Length) DisplaySyntax();
        else DisplayTypeInfo(args[0]);
    }
}

 

2.创建

(1)多类间根据需要动态地创建对象,主要是System.Activator类,CreateInstance(type parameter)方法,如下:

using System;
using System.Reflection;

class AbstractFactory 
{
    public IReflect CreateObject(string classname)
    {
        IReflect objreflect;
        try
        {
            // Create the type, throwing an exception
            // if it can't be created.
            System.Type oType = System.Type.GetType(classname,true);

            // Create an instance and type-cast it
            // to our interface.
            objreflect =
                (IReflect)System.Activator.CreateInstance(
                oType);
        }
        catch(TypeLoadException e)
        {
            throw new InvalidOperationException("Type could " +
                "not be created. Check innerException " +
                "for details", e);
        }

        return objreflect; 
    }
};

public interface IReflect
{
    string Name { get; }
};

class Reflect1 : IReflect
{
    public string Name 
    { 
        get { return "Reflect 1"; } 
    }
};

class Reflect2 : IReflect
{
    public string Name 
    { 
        get { return "Reflect 2"; } 
    }
}

class AbstractFactoryApp
{
    static void Main(string[] args)
    {
        callReflection(args[0]);
    }

    static void callReflection(string strClassName)
    { 
        IReflect objReflect;

        AbstractFactory objFactory = new AbstractFactory();

        try
        {
            objReflect = objFactory.CreateObject(strClassName);
            Console.WriteLine("You constructed a {0} object",
                objReflect.Name);
        }
        catch(Exception e)
        {
            Console.WriteLine("ERROR: {0}\n{1}", 
                e.Message,
               (null == e.InnerException ?
               "" : e.InnerException.Message));
        }

        Console.ReadLine();
    }
};

 

 (2)全程创建(类型及对象)

// ILGenServer.cs – compile as follows:
// csc /t:library ILGenServer.cs
using System;
using System.Reflection;
using System.Reflection.Emit;

namespace ILGenServer
{
    public class CodeGenerator
    {
        public CodeGenerator()
        {
            // Get current currentDomain.
            currentDomain = AppDomain.CurrentDomain;

            // Create assembly in current currentDomain.
            assemblyName = new AssemblyName();
            assemblyName.Name = "TempAssembly";

            assemblyBuilder = 
                currentDomain.DefineDynamicAssembly(
                assemblyName,
                AssemblyBuilderAccess.Run);

            // Create a module in the assembly.
            moduleBuilder = 
                assemblyBuilder.DefineDynamicModule(
                "TempModule");

            // Create a type in the module.
            typeBuilder = 
                moduleBuilder.DefineType("TempClass",
                TypeAttributes.Public);

            // Add a member (a method) to the type. 
            methodBuilder = typeBuilder.DefineMethod(
                "HelloWorld", MethodAttributes.Public,
                null, null);

            // Generate MSIL.
            msil = methodBuilder.GetILGenerator();
            msil.EmitWriteLine("Hello World");
            msil.Emit(OpCodes.Ret);

            // Last "build" step : create type.
            type = typeBuilder.CreateType();
        }

        AppDomain currentDomain;
        AssemblyName assemblyName;
        AssemblyBuilder assemblyBuilder;
        ModuleBuilder moduleBuilder;
        TypeBuilder typeBuilder;
        MethodBuilder methodBuilder;
        ILGenerator msil;
        object obj;

        Type type;
        public Type T
        { 
            get { return this.type; } 
        }
    }; // End of CodeGenerator class
}; // End of ILGenServer namespace

 

 

客户端调用上面编译后的dll,如下:

// ILGenClient.cs – compile as follows:
// csc ILGenClient.cs /r:ILGenServer.dll
using System;
using System.Reflection;
using ILGenServer;

public class ILGenClientApp
{
    public static void Main()
    {
        Console.WriteLine("Calling DLL function to generate " + 
            "a new type and method in memory...");
        CodeGenerator gen = new CodeGenerator();

        Console.WriteLine("Retrieving dynamically " +
            "generated type...");
        Type t = gen.T;
        if (null != t)
        {
            Console.WriteLine("Instantiating the new type...");
            object o = Activator.CreateInstance(t);

            Console.WriteLine("Retrieving the type's " +
                "HelloWorld method...");
            MethodInfo helloWorld = t.GetMethod("HelloWorld");
            if (null != helloWorld)
            {
                Console.WriteLine("Invoking our dynamically " +
                    "created HelloWorld method...");
                helloWorld.Invoke(o, null);
            }
            else
            {
                Console.WriteLine("Could not locate " +
                    "HelloWorld method");
            }
        }
        else
        {
            Console.WriteLine("Could not access Type " +
                "from server");
        }
    }
}

 

小结,如果说“委托”实现了对同构函数(类成员层面)的抽象,那么“反射”提供了对“同性对象”(类层面)全面的动态运行时干预能力。而对于latebinding,则更是直接衍生出了一种新的语法格式,即泛型(generics),一般用<T>表示。即,在运行时由客户端来确定实际的类型(也就是说,类型可变)。

 

   

分享到:
评论

相关推荐

    Unity实现镜面反射

    以下我们将详细探讨如何在Unity中实现镜面反射。 首先,镜面反射的核心在于使用特殊的Shader(着色器)。Shader是一种编程语言,用于控制游戏对象在屏幕上显示的颜色和外观。在Unity中,我们通常使用基于Unity ...

    java反射实现Junit3框架

    在本主题中,我们将深入探讨如何利用Java反射来实现JUnit3框架,即使我们不知道具体的类名。JUnit3是Java单元测试的一个早期版本,它提供了编写和执行测试用例的框架。 首先,理解反射的基本概念是必要的。在Java中...

    利用反射 实现一个自制的struts

    然而,这个资源是关于如何利用反射机制来创建一个自制的Struts框架的实践。反射在Java中是一个强大的工具,它允许程序在运行时检查和操作类、接口、字段和方法的信息,甚至可以动态调用方法。 首先,我们需要理解...

    C++反射机制实现

    在讨论C++反射机制实现的过程中,我们首先需要明确反射机制的概念和分类。反射的定义源自人工智能领域,它主要涉及到两种反射结构:结构反射和计算反射。结构反射侧重于元类与类之间的关系,计算反射则关注于计算...

    c++实现反射demo

    然而,目前这一特性尚未被所有编译器广泛支持,所以对于需要在现有环境工作的项目,上述自定义的反射实现仍然有其价值。 总的来说,"C++实现反射demo"展示了如何利用C++的模板和宏技术,模拟出类似于其他语言中的...

    反射工厂实现mvc

    希望喜欢, 反射工厂实现mvc

    利用反射实现类的动态加载

    ### 利用反射实现类的动态加载 #### 反射技术简介 反射是Java语言提供的一种强大特性,允许运行时动态地获取类的信息并操纵类的对象。这种能力使得开发人员能够在编写程序时不确定具体类的情况下,依然能实现对类...

    java反射实现数据库操作Dao

    java反射实现数据库增、删、改、查操作Dao

    c++ 反射实现原理代码;

    c++ 反射实现原理代码;c++ 反射实现原理代码;c++ 反射实现原理代码;c++ 反射实现原理代码;c++ 反射实现原理代码;

    C++实现反射机制

    在C++中实现反射,我们需要创建一个元信息系统来存储关于类、函数、变量等的信息。这通常涉及到定义一系列的结构体或类,如`ClassInfo`、`MethodInfo`和`FieldInfo`,以及相关的注册和查询机制。 ```cpp struct ...

    java反射实现javabean转json实例代码.docx

    ### Java反射机制实现JavaBean转JSON的详细解析 #### 一、引言 在现代软件开发过程中,数据格式转换是一项非常常见的任务。特别是在处理不同系统之间的数据交换时,JSON(JavaScript Object Notation)因其轻量级...

    反射实现 AOP 动态代理模式(Spring AOP 的实现原理)

    在使用反射实现AOP动态代理时,我们也需要注意一些问题。例如,由于代理类是在运行时动态创建的,这可能会影响程序的性能,特别是在频繁调用代理方法的情况下。因此,在实际开发中,需要根据应用场景的性能要求和...

    Java反射泛型,实现数据库的动态增删改查等功能

    具体实现时,我们可以为每个数据库操作创建一个泛型方法,使用反射获取实体类的字段,根据字段生成对应的SQL语句片段。比如在插入操作中,我们可以遍历`T`的所有字段,构建一个`INSERT INTO table_name (field1, ...

    自定义Dao,反射实现

    自定义Dao并通过反射实现,虽然比使用ORM框架(如Hibernate、MyBatis)更繁琐,但可以更好地控制SQL语句,避免了不必要的映射配置。这种方法适用于小型项目或对性能有较高要求的场景,同时也为学习Java反射机制提供...

    利用反射实现的增删改查操作的底层代码

    在给定的“利用反射实现的增删改查操作的底层代码”中,我们可以深入理解如何通过反射机制简化JDBC(Java Database Connectivity)的数据库操作,如增加(Insert)、删除(Delete)、更新(Update)和查询(Query)...

    winform 反射工厂模式的实现源码

    1. **反射**:反射是.NET框架提供的一种能力,它允许运行中的代码获取关于自身类型的信息,并能动态地创建和操作对象。通过反射,我们可以在运行时检查类、接口、字段、方法等元数据,甚至可以动态地实例化对象、...

    基于反射实现C#编辑器

    本项目“基于反射实现C#编辑器”聚焦于使用C#编程语言和反射技术来构建一个可扩展的编辑器,这为软件的二次开发提供了一个强大的工具。 C#是一种面向对象的、类型安全的编程语言,广泛应用于Windows桌面应用、Web...

    反射实现 AOP 动态代理模式(Spring AOP 的实现 原理) - Java 例子 -

    本文将深入探讨Spring AOP的实现原理,以及如何使用反射来实现动态代理模式。 首先,我们需要了解AOP的基本概念。AOP的核心思想是切面,它包含两个主要部分:切点(Pointcut)和通知(Advice)。切点定义了在程序...

Global site tag (gtag.js) - Google Analytics