问题描述
我有一个第三方程序集,我想在我的新 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
的要点访问修饰符 是使其仅在定义的类的程序集中可用.
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")]
如果不是,您总是可以使用反射,但请注意,在 3rd 方程序集上使用反射是危险的,因为它可能会被供应商更改.你也可以反编译 整个程序集并尽可能使用您想要的部分代码.
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();
}
}
}
这篇关于如何使用另一个程序集的内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!