<分区>
我有一个第三方程序集,我想在我的新 C# 项目中使用它的 Internal
类。
可能吗?
任何例子都将不胜感激
标签 c# .net oop .net-assembly
<分区>
我有一个第三方程序集,我想在我的新 C# 项目中使用它的 Internal
类。
可能吗?
任何例子都将不胜感激
最佳答案
internal: The type or member can be accessed by any code in the same assembly, but not from another assembly.
不能使用其他程序集的内部类,使用internal
的要点access modifier是使其仅在定义的类的程序集内可用。
如果您有权访问汇编代码并且可以修改它,则可以将第二个汇编作为 friend您当前的程序集并使用以下属性标记程序集
[assembly: InternalsVisibleTo("name of assembly here")]
如果不是,您始终可以使用反射,但请注意,在第 3 方程序集上使用反射是危险的,因为它可能会被供应商更改。你也可以decompile整个程序集,并尽可能使用您想要的部分代码。
假设你有这个 dll(mytest.dll 说):
using System;
namespace MyTest
{
internal class MyClass
{
internal void MyMethod()
{
Console.WriteLine("Hello from MyTest.MyClass!");
}
}
}
并且您想创建 MyTest.MyClass
的实例,然后使用反射从另一个程序调用 MyMethod()
。方法如下:
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();
}
}
}
关于c# - 如何使用另一个程序集的内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27334013/