获取调用C#方法的实例
我正在寻找一种算法,可以在该方法中获取调用该方法的对象。
例如:
public class Class1 {
public void Method () {
//the question
object a = ...;//the object that called the method (in this case object1)
//other instructions
}
}
public class Class2 {
public Class2 () {
Class1 myClass1 = new Class1();
myClass1.Method();
}
public static void Main () {
Class2 object1 = new Class2();
//...
}
}
有什么办法可以做到这一点吗?
I am looking for an algorithm that can get the object that called the method, within that method.
For instance:
public class Class1 {
public void Method () {
//the question
object a = ...;//the object that called the method (in this case object1)
//other instructions
}
}
public class Class2 {
public Class2 () {
Class1 myClass1 = new Class1();
myClass1.Method();
}
public static void Main () {
Class2 object1 = new Class2();
//...
}
}
Is there any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是如何执行此操作的示例...
发布此内容是因为我花了一段时间才找到我自己正在寻找的内容。我在一些静态记录器方法中使用它......
Here's an example of how to do this...
Posting this, because it took me a while to find what I was looking for myself. I'm using it in some static logger methods...
您可以在代码中找到当前的堆栈跟踪并向上移动一步。
http://msdn.microsoft.com/en-us/ library/system.diagnostics.stacktrace.aspx
但正如下面评论的那样,这将为您提供调用您的方法和类,但不是实例(如果有的话,当然可能是静态的)。
You could get to the current stack trace in code and walk up one step.
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx
But as was commented below, this will get you the method and class calling you, but not the instance (if there is one, could be a static of course).
或者只是将对象作为方法参数传递。
并调用方法:
问候,弗洛里安
or just pass the object as method parameter.
and call the Method:
regards, Florian
显然,我不知道您情况的确切细节,但这似乎您确实需要重新考虑一下您的结构。
如果构建适当的继承,这可以很容易地完成。
考虑研究一个抽象类和从该抽象类继承的类。您甚至可以使用接口来完成同样的事情。
Obviously i don't know the exact details of your situation but this really seems like you need to rethink your structure a bit.
This could easily be done if proper inheritance is structured.
Consider looking into an abstract class and classes that inherit from said abstract class. You might even be able to accomplish the same thing with interfaces.