可以用 lambda 函数重写方法吗
有没有办法用 lambda 函数重写类方法?
例如,有一个
class MyClass {
public virtual void MyMethod(int x) {
throw new NotImplementedException();
}
}
Is There All to do 的类定义:
MyClass myObj = new MyClass();
myObj.MyMethod = (x) => { Console.WriteLine(x); };
Is there any way to override a class method with a lambda function?
For example with a class definition of
class MyClass {
public virtual void MyMethod(int x) {
throw new NotImplementedException();
}
}
Is there anyway to do:
MyClass myObj = new MyClass();
myObj.MyMethod = (x) => { Console.WriteLine(x); };
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
克里斯是对的,方法不能像变量一样使用。 但是,您可以执行以下操作:
要允许覆盖该操作:
Chris is right that methods cannot be used like variables. However, you could do something like this:
To allow the action to be overridden:
不。但是,如果您首先将该方法声明为 lambda,则可以设置它,尽管我会尝试在初始化时这样做。
但是,这无法实现声明了 MyMethod 的接口,除非该接口指定了 lambda 属性。
F# 具有对象表达式,允许您使用 lambda 组合对象。 我希望在某个时候这是 C# 的一部分。
No. However if you declare the method as a lambda in the first place, you can set it, though I would try to do that at initialization time.
This however cannot implement an interface that has a MyMethod declared, unless the interface specifies a lambda property.
F# has object expressions, which allow you to compose an object out of lambdas. I hope at some point this is part of c#.
不可以。方法不能像变量一样使用。
如果您使用 JavaScript,那么是的,您可以这样做。
No. Methods cannot be used like variables.
If you were using JavaScript, then yes, you could do that.
您可以编写以下代码:
如果您以这种方式定义 MyClass:
但这应该不会太令人惊讶。
You can write this code:
If you define MyClass in this way:
But that shouldn't be too surprising.
不是直接的,但是用一点代码就可以了。
那么你可以有代码
Not directly, but with a little code it's doable.
then you could have code
根据您想要做什么,有很多方法可以解决这个问题。
一个好的起点是创建一个可获取和可设置的委托(例如操作)属性。 然后,您可以拥有一个委托该操作属性的方法,或者直接在客户端代码中调用它。 这开辟了很多其他选项,例如使操作属性私有可设置(也许提供一个构造函数来设置它)等
。
Depending on what you want to do, there are many ways to solve this problem.
A good starting point is to make a delegate (e.g. Action) property that is gettable and settable. You can then have a method which delegates to that action property, or simply call it directly in client code. This opens up a lot of other options, such as making the action property private settable (perhaps providing a constructor to set it), etc.
E.g.