我有一个 dll,包括:
public abstract class Module
{
internal int ID;
public abstract void ModuleStart();
}
public void function1() {}
public void function2() {}
//etc...
然后我有另一个引用上述 dll 的 dll 并具有:
class MyModule : Module
{
public override void ModuleStart()
{
function1();
}
}
我想做的是让 function1 知道调用模块 ID 的值,而不是传入它。有没有办法做到这一点?基本上我想做的是,加载主模块 DLL,运行一个加载第二个 dll 的方法,使用反射来确保它有模块的子级,为其分配一个 ID 并运行 ModuleStart。然后 MyModule 可以做它需要的事情,从第一个 dll 调用函数以访问内部 protected 内存,但是当函数被调用时,它们需要知道调用它们的模块的 ID。这可能吗? MyModule 不知道其 ID,也无法更改它。
最佳答案
.NET 4.5 添加了一些功能来对 CallerMemberNameAttribute
执行类似的操作.这是来自文档的示例:
public void TraceMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace.WriteLine("message: " + message);
Trace.WriteLine("member name: " + memberName);
Trace.WriteLine("source file path: " + sourceFilePath);
Trace.WriteLine("source line number: " + sourceLineNumber);
}
关于c# - 获取对调用方法的对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14865478/