将Activity上下文传递给构造函数以在内部使用-这不好 [英] Passing Activity Context to constructors to use internally - is this bad
问题描述
将Context传递给构造函数并将其另存为私有变量以供内部使用是不好的做法吗?另一种选择是将Context作为参数传递给需要它的方法.
Is it bad practice to pass the Context to a constructor and save it as a private variable for internal use? The other option is to pass the Context as a parameter to methods that need it.
哪个是更好的选择? 我觉得传递给构造函数可能会导致内存意外泄漏.
Which is a better option? I have a feeling that passing to the constructor might result in memory leaks accidentally.
推荐答案
通常,您只需要ApplicationContext
,因此您所要做的就是传递this.getApplicationContext()
而不是仅仅this
.无论如何,您的应用程序上下文在应用程序的生存期内都存在,因此这不是内存泄漏.
Often, all you need is the ApplicationContext
, so what you can do is pass this.getApplicationContext()
instead of just this
. Your app context exists for the lifetime of the app anyway, so it's not a memory leak.
这篇关于将Activity上下文传递给构造函数以在内部使用-这不好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!