[英]How can I figure out which object created this object
Is there an easy way to get the object that created this object. 有没有一种简单的方法来获取创建该对象的对象。 I know that it will always be of some object type, but I was hoping for some easy keyword to use like
this
while in the constructor. 我知道它将始终是某种对象类型,但是我希望在构造函数中使用一些简单的关键字来像
this
。
I have been creating unit tests for this add-in I am working on in PowerPoint. 我一直在为在PowerPoint中工作的此外接程序创建单元测试。 Sometimes you need to go one level up and look at the parent object to get information such as position, font size, etc. I tried to avoid this up until now.
有时您需要上一层查看父对象以获取诸如位置,字体大小等信息。我一直尝试避免这种情况。
I suppose I can edit my "Mocks" and add another constructor where I pass the object that creates each object to its child; 我想我可以编辑“ Mocks”并添加另一个构造函数,将创建每个对象的对象传递给它的子对象。 however, I feel like there is a better solution out there.
但是,我觉得那里有更好的解决方案。 Oh also, these mocks are partially implementing interfaces provided by Visual Studios Tools for Office and part of their interface is the
Parent
property getter/setter. 另外,这些模拟部分实现了Visual Studios Tools for Office提供的接口,它们的一部分接口是
Parent
属性的getter / setter。 If I don't implement a method it simply throws a new NotImplementedException
when that method is called. 如果我不实现方法,则在调用该方法时,它只会引发一个新的
NotImplementedException
。
You can get the calling method from the stack, and deduce the class name from that: 您可以从堆栈中获取调用方法,并从中推导出类名:
http://www.csharp-examples.net/reflection-calling-method-name/ http://www.csharp-examples.net/reflection-calling-method-name/
However, this is fragile in the sense that, if you ever have a layer inbetween, the position of the caller you care about in the stack would shift. 但是,从某种意义上说,这是脆弱的,如果您之间有一层,则您关注的调用方在堆栈中的位置会发生变化。 If you place the logic in a utility method or extension method, though, it would not be hard to evolve over time.
但是,如果将逻辑放在实用程序方法或扩展方法中,则随着时间的推移将变得很困难。
Querying the call stack is not a terribly fast operation, but for unit tests, it would probably be acceptable. 查询调用堆栈并不是一个非常快速的操作,但是对于单元测试,这可能是可以接受的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.