问题描述
Container(
width: MediaQuery.of(context).size.width,height: 40.0,color: Colors.green,child: Row(
crossAxisAlignment: CrossAxisAlignment.end,children: <Widget>[
Expanded(
flex: 5,child: Container(
height: 40.0,child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0),),color: Colors.pink,onpressed: () {},child: Text('BUY Now'),Expanded(
flex: 1,child: InkWell(
onTap: () {},child: Container(
child: Icon(
Icons.favorite,size: 37.0,color: Colors.red,child: Container(
child: Icon(
Icons.shopping_cart,],)
但是,我想在该类的所有方法中使用此lambda。如何在全班学习?
我尝试过这样的事情:
class MyClass
def test
to_cross = lambda do |m,x| # Just a dummy example
return m * x
end
to_cross.call(7,9)
end
def another_method
to_cross = lambda do |m,x| # Just a dummy example
return m * x
end
to_cross.call(2,5)
end
end
我知道了
class MyClass
# Define in class
to_cross = lambda do |m,x| # Just a dummy example
return m * x
end
def test
to_cross.call(2,5)
end
def another_method
to_cross.call(2,5)
end
end
我有什么选择?如何在undefined local variable or method `to_cross' for #<MyClass:0x0000564193f4e748>
中的所有方法中使用此lambda?有哪些选择和优点/缺点?
解决方法
使用实例变量
您可以将Proc或lambda存储为实例变量。然后,您可以从类中的任何方法访问该变量。例如:
class MyClass
def initialize
# make the lambda accessible throughout the
# class as an instance variable
@to_cross = ->(m,x) { m * x }
end
def test
@to_cross.call 7,9
end
def another_method
@to_cross.call 2,5
end
end
klass = MyClass.new
klass.test #=> 63
klass.another_method #=> 10
主要要点是将lambda存储在一个范围内,该范围可从您的实例或类中的其他方法进行访问,或者将lambda作为参数显式传递。如果将其存储为变量,则实例变量,类变量或类/模块常量的选择将取决于多种因素,但是实例变量通常是正确的泛型选择。
,您不能从class方法中访问类局部变量。以同样的方式
x=5
def f
x
end
不起作用;调用f
时收到语法错误,因为未定义x
。
从技术上讲,您可以在类(@to_cross
)或类变量(@@to_cross
)中使用实例变量,甚至可以在全局变量($to_cross
中使用实例变量,尽管使用情况很好后者很少见。如果您不打算重新分配常量,也可以使用常量(To_cross
)(但是,当然,我们想知道为什么要从lambda分配变量,而不仅仅是类方法)
因此,在决定如何建模此lamda之前,我会考虑
- 在何处以及如何调用它,以及
- 您将从何处修改此变量
在您的情况下,您只是说要从每个实例方法中调用它,这意味着您不应使用带有lambda的变量,而应使用(可能是私有的)实例方法或类方法。由于示例中的to_cross
似乎没有访问任何其他实例方法或实例变量,因此也许最好使用类方法:
def self.to_cross(m,x)
m*x
end
然后您将其称为
def another_method
self.class.to_cross.call(2,5)
end