C#中反射的运用

namespace System.Reflection

//加载相关的dll程序集

public static Assembly Load(string assemblyString); 

//获取类型。如果当string表示的目标类型不在当前程序集中,则运行时Type.GetType会返回null。解决 的办法是:首先加载目标程序集,然后再使用Assembly.GetType方法来获取类型。

public virtual Type GetType(string name);

Type.GetConstructor Method (System) | Microsoft Docs

//Gets a specific constructor of the current Type 获取当前类的构造函数, Type[] types 用来支持不同入参的构造函数 

public ConstructorInfo GetConstructor(Type[] types);

从简单的案例开始

class Invoke{ public static void Main() { Type type = typeof(StringBuilder); Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) }; ConstructorInfo cInfo = type.GetConstructor(argTypes); object[] argVals = new object[] { "Some string", 30 }; // Create the object and cast it to StringBuilder. StringBuilder invoke = (StringBuilder)cInfo.Invoke(argVals); StringBuilder direct = new StringBuilder("Some string", 30); if (invoke.Equals(direct)) { Console.WriteLine("Expected"); } }}


接下来我们来看一个具体的案例

private static IVstaHelper GetVstaHelper()

        {

            Assembly helperAssembly;

           string assemblyName = "Microsoft.SqlServer.IntegrationServices.VSTA.VSTA16, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91";

            try

            {

                //完成相关dll的load

                helperAssembly = Assembly.Load(assemblyName);

            }

            catch (FileNotFoundException)

            {

                s_tc.TraceError("Cannot load assembly {0}", assemblyName);      // do not localize

                throw new FileNotFoundException(assemblyName);

            }

            string typeName = "Microsoft.SqlServer.IntegrationServices.VSTA.VstaHelper";    

            //在 VSTA16的程序集中获取到VstaHelper类型

            Type helperType = helperAssembly.GetType(typeName);

            if (helperType == null)

            {

                s_tc.TraceError("Cannot load type {0}", typeName);      // do not localize

                throw new Exception(Localized.FailedToCreateVSTAHelper);

            }

            //选择了VstaHelper参数为空的构造函数

            ConstructorInfo cinfo = helperType.GetConstructor(new Type[] { });

            if (cinfo == null)

            {

                s_tc.TraceError("Cannot get VstaHelper constructor info");          // do not localize

                throw new Exception(Localized.FailedToCreateVSTAHelper);

            }

            //回调构造函数,生成IVstaHelper

            IVstaHelper result = cinfo.Invoke(null) as IVstaHelper;

            if (result == null)

            {

                s_tc.TraceError("Cannot instantiate VstaHelper object");          // do not localize

                throw new Exception(Localized.FailedToCreateVSTAHelper);

            }

            return result;

        }


还有一个类似的问题 我们的项目因为一些依赖的原因 必须在csproj引入Microsoft.SqlServer.WizardFramework 15.0 但是我们的项目下游需要一个16.0的传参 于是:

void copyFromVersion15toVersion16(WizardInputs  importWizardInputs ) {

string assemblyName = "Microsoft.SqlServer.WizardFramework, Version=16.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91";                

Assembly assembly = Assembly.Load(assemblyName);                

string typeName = "Microsoft.SqlServer.Management.UI.WizardInputs";                

Type dType = assembly.GetType(typeName);                

ConstructorInfo cinfo = dType.GetConstructor(new Type[] { });               

importWizardInputstemp = cinfo.Invoke(null);              

Type sType = typeof(WizardInputs);                

foreach (PropertyInfo now in sType.GetProperties())                { 

                   var name = dType.GetProperty(now.Name);                                        if (name == null)                        continue;                                      dType.GetProperty(now.Name).SetValue(importWizardInputstemp, now.GetValue(importWizardInputs));                

    }           

 }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 概念 反射机制是使程序具有动态特性的非常关键的一种机制 需求1:根据指定的类名,类字段名和所对应的数据,得到该类的...
    沉麟阅读 1,107评论 0 0
  • 转自博客园 反射是.NET中的重要机制,通过反射,可以在运行时获得程序或程序集中每一个类型(包括类、结构、委托、接...
    极客诗人阅读 999评论 0 0
  • 上学时学习C#和.NET,当时网上的资源不像现在这样丰富,所以去电脑城买了张盗版的VS2005的光盘,安装时才发现...
    编程小世界阅读 353评论 0 0
  • 今天稍微看了下反射的东西,虽然还不是很明白,但也写写随笔,加深下印象。 1、反射是什么东西? Refl...
    北风知我意阅读 1,298评论 0 0
  • 什么是反射 反射 [Reflection]:是.Net中获取运行时类型信息的方式,.Net的应用程序共有三个部分:...
    passiony阅读 557评论 0 3

友情链接更多精彩内容