Swift中的懒惰变量是不是一次计算过的?我的印象是他们取代了:
if (instanceVariable) {
return instanceVariable;
}
// set up variable that has not been initialized
Run Code Online (Sandbox Code Playgroud)
来自Objective-C的范例(懒惰的实例化).
那是他们做的吗?基本上只在第一次应用程序要求变量时调用,然后才返回计算的内容?
或者它每次都像普通的计算属性一样被调用?
我问的原因是因为我基本上想在Swift中有一个可以访问其他实例变量的计算属性.假设我有一个名为"fullName"的变量,它只是连接firstName和lastName.我怎么会在Swift中这样做?似乎懒惰变量是唯一的方法,因为在正常的计算变量(非惰性)中我无法访问其他实例变量.
所以基本上:
Swift中的懒惰变量不止一次被调用吗?如果是这样,我如何创建一个可以访问实例变量的计算变量?如果没有,如果出于性能原因我只想要计算一次变量,我该怎么做?
所以我kotlin用于android,当膨胀视图时,我倾向于做以下事情:
private val recyclerView by lazy { find<RecyclerView>(R.id.recyclerView) }
Run Code Online (Sandbox Code Playgroud)
这种方法可行.但是,有一种情况会导致应用程序出错.如果这是一个片段,并且片段转到backstack,onCreateView将再次调用,并且将重新创建片段的视图层次结构.这意味着,懒惰启动的recyclerView将指出不再存在的旧视图.
解决方案是这样的:
private lateinit var recyclerView: RecyclerView
Run Code Online (Sandbox Code Playgroud)
并初始化内部的所有属性onCreateView.
我的问题是,有没有办法重置懒惰属性,以便可以再次初始化它们?我喜欢这样的事实:初始化都是在类的顶部完成的,有助于保持代码的有序性.具体问题是在这个问题中找到的:kotlin android片段后面的空循环器视图
使用惰性初始化器时,是否有可能保留周期?
在博客文章和许多其他地方[unowned self]可见
class Person {
var name: String
lazy var personalizedGreeting: String = {
[unowned self] in
return "Hello, \(self.name)!"
}()
init(name: String) {
self.name = name
}
}
Run Code Online (Sandbox Code Playgroud)
我试过这个
class Person {
var name: String
lazy var personalizedGreeting: String = {
//[unowned self] in
return "Hello, \(self.name)!"
}()
init(name: String) {
print("person init")
self.name = name
}
deinit {
print("person deinit")
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它
//...
let person = Person(name: "name")
print(person.personalizedGreeting)
//..
Run Code Online (Sandbox Code Playgroud)
并发现"人员deinit"被记录下来.
所以似乎没有保留周期.根据我的知识,当一个块捕获自我并且当该块被自己强烈保留时,存在保留周期.这种情况看起来类似于保留周期但实际上并非如此.
memory-leaks memory-management lazy-initialization automatic-ref-counting swift
我想知道初始化类成员的python方法是什么,但只有在访问它时才会访问它.我尝试了下面的代码并且它正在运行,但有什么比这简单吗?
class MyClass(object):
_MY_DATA = None
@staticmethod
def _retrieve_my_data():
my_data = ... # costly database call
return my_data
@classmethod
def get_my_data(cls):
if cls._MY_DATA is None:
cls._MY_DATA = MyClass._retrieve_my_data()
return cls._MY_DATA
Run Code Online (Sandbox Code Playgroud) 我试图使用通用的Lazy类来实例化.net核心依赖注入扩展的昂贵类.我已经注册了IRepo类型,但我不确定Lazy类的注册是什么样的,或者它是否支持.作为一种解决方法,我使用了这种方法http://mark-dot-net.blogspot.com/2009/08/lazy-loading-of-dependencies-in-unity.html
配置:
public void ConfigureService(IServiceCollection services)
{
services.AddTransient<IRepo, Repo>();
//register lazy
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public class ValuesController : Controller
{
private Lazy<IRepo> _repo;
public ValuesController (Lazy<IRepo> repo)
{
_repo = repo;
}
[HttpGet()]
public IActionResult Get()
{
//Do something cheap
if(something)
return Ok(something);
else
return Ok(repo.Value.Get());
}
}
Run Code Online (Sandbox Code Playgroud) c# dependency-injection lazy-initialization .net-core asp.net-core
我想在我的Entites中使用System.Lazy来懒惰初始化我的列表:
public class Questionary
{
private Lazy<List<Question>> _questions = new Lazy<List<Question>>(() => new List<Question>());
public IList<Question> Questions { get { return _questions.Value; } set { _questions.Value = value; } }
}
Run Code Online (Sandbox Code Playgroud)
问题出在我的SETTER上,得到这个错误:属性' System.Lazy<T>.Value'没有setter
如果我想做MyInstance.Questions = new List<Question> { ... }?
我该怎么办?
更新:
我试图避免这种情况:
private IList<Question> _questions;
//Trying to avoid that ugly if in my getter:
public IList<Question> Questions { get { return _questions == null ? new List<Question>() : _questions; } set { _questions = value …Run Code Online (Sandbox Code Playgroud) 似乎我遇到了一些不应该出现问题的问题......但我想请求一些帮助.
这里有一些解释我没有得到.
有两个简单的类,其中一个引用另一个,如下所示;
class User {
lazy var name: String = ""
lazy var age: Int = 0
init (name: String, age: Int) {
self.name = name
self.age = age
}
}
class MyOwn {
let myUser: User = User(name: "John", age: 100)
var life = myUser.age
//Cannot use instance member 'myUser' within property initializer
//property initializers run before 'self' is available
}
Run Code Online (Sandbox Code Playgroud)
我得到了注释编译错误.请有人告诉我该怎么办才能解决这个案子?
非常感谢任何好人的帮助!
使用spark,有时我需要在每个任务中发送一个不可序列化的对象.
常见的模式是@transient lazy val,例如
class A(val a: Int)
def compute(rdd: RDD[Int]) = {
// lazy val instance = {
@transient lazy val instance = {
println("in lazy object")
new A(1)
}
val res = rdd.map(instance.a + _).count()
println(res)
}
compute(sc.makeRDD(1 to 100, 8))
Run Code Online (Sandbox Code Playgroud)
我发现@transient这里没有必要.lazy val可以在执行每个任务时创建非序列化.但人们建议使用@transient.
有什么好处,如果我们在序列化时设置@transient非初始化lazy val?
val为序列化创建一个非初始化瞬态是否有意义,知道没有任何序列化,就像上面的例子一样?
如何@transient lazy val序列化?它被视为一种方法还是其他什么?
有关序列化@transient lazy val和编译的java字节码的一些细节非常棒.
serialization scala transient lazy-initialization apache-spark
我正在尝试实现这样的程序结构:

这里的问题是,当开头没有明显的控制器使用功能时,它们没有实例化而没有注册FeatureRegistry,因此它们无法显示在视图中.但我想要实现的是它们出现在视图中,然后通过模板加载ng-include,然后在模板中有每个特性的特定控制器.这些控制器是使用功能的控制器.
这些功能基本上只用于说明要使用的模板和图标的位置,以及启动功能的开始.
但回到我最初的问题:
即使现在不需要服务,如何实例化服务呢?
或者是否有其他功能,我可以使用它而不是服务?我还想如果你指出我那么:)
lazy-loading lazy-initialization angularjs angularjs-service
Dart、Kotlin 和 Swift 有一个延迟初始化关键字,主要出于可维护性的原因,可以让您避免使用可选类型。
// Using null safety:
class Coffee {
late String _temperature;
void heat() { _temperature = 'hot'; }
void chill() { _temperature = 'iced'; }
String serve() => _temperature + ' coffee';
}
Run Code Online (Sandbox Code Playgroud)
TypeScript 有什么等价物?
null initialization lazy-initialization typescript option-type
swift ×3
c# ×2
properties ×2
.net ×1
.net-core ×1
android ×1
angularjs ×1
apache-spark ×1
asp.net-core ×1
c#-4.0 ×1
class ×1
init ×1
kotlin ×1
lazy-loading ×1
memory-leaks ×1
null ×1
option-type ×1
python ×1
scala ×1
transient ×1
typescript ×1