如何使用另一个程序集的内部类 [英] How to use internal class of another Assembly

查看:112
本文介绍了如何使用另一个程序集的内部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个第三方程序集,我想在我的新C#项目中使用它的Internal类. 有可能吗?

I have a third party assembly and I would like to use its Internal class in my new C# project. Is it possible?

任何例子都将不胜感激

推荐答案

内部:类型或成员可以通过同一代码中的任何代码访问 程序集,而不是另一个程序集.

internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.

您不能使用其他程序集的内部类,使用internal 访问修饰符使其仅在定义的类的程序集中可用.

You can not use internal classes of other assemblies, the point of using internal access modifier is to make it available just inside the assembly the class defined.

如果您有权访问程序集代码并且可以对其进行修改,则可以将第二个程序集作为朋友,并使用以下属性标记该程序集

if you have access to the assembly code and you can modify it you can make second assembly as a friend of your current assembly and mark the assembly with following attribute

[assembly: InternalsVisibleTo("name of assembly here")]

如果不是这样,您始终可以使用反射,但是请注意,在第三方装配体上使用反射是危险的,因为供应商可能会对其进行更改.您也可以反编译整个程序集,并在可能的情况下使用所需代码的一部分.

if not you can always use reflection but be aware that using reflection on a 3rd party assembly is dangerous because it is subject to change by the vendor. you can also decompile the whole assembly and use part of the code you want if it is possible.

假设您有这个dll(例如mytest.dll):

Suppose you have this dll (mytest.dll say):

using System; 

namespace MyTest 
{ 
      internal class MyClass 
      {  
          internal void MyMethod() 
          {  
               Console.WriteLine("Hello from MyTest.MyClass!"); 
          } 
      } 
} 

,您想创建MyTest.MyClass的实例,然后使用反射从另一个程序中调用MyMethod().这样做的方法:

and you want to create an instance of MyTest.MyClass and then call MyMethod() from another program using reflection. Here's how to do it:

using System; 
using System.Reflection;

namespace MyProgram 
{ 
    class MyProgram 
    { 
          static void Main() 
          { 
              Assembly assembly = Assembly.LoadFrom("mytest.dll");
              object mc = assembly.CreateInstance("MyTest.MyClass");
              Type t = mc.GetType(); 
              BindingFlags bf = BindingFlags.Instance |  BindingFlags.NonPublic;
              MethodInfo mi = t.GetMethod("MyMethod", bf); 
              mi.Invoke(mc, null); 
              Console.ReadKey(); 
         } 
    } 
}  

这篇关于如何使用另一个程序集的内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆