一个方法能否使用lambda函数来覆盖重写?

3
有没有办法用lambda函数覆盖类方法?
例如,有一个类定义:
class MyClass {  
    public virtual void MyMethod(int x) {
        throw new NotImplementedException();
    }
}

有没有什么办法可以实现以下功能:

MyClass myObj = new MyClass();
myObj.MyMethod = (x) => { Console.WriteLine(x); };
6个回答

6

克里斯是正确的,方法不能像变量一样使用。但是,您可以这样做:

class MyClass {
    public Action<int> MyAction = x => { throw new NotImplementedException() };
}

为允许覆盖该操作:

MyClass myObj = new MyClass();
myObj.MyAction = (x) => { Console.WriteLine(x); };

5

不可以。但是如果你一开始将方法声明为lambda表达式,那么你可以设置它,尽管我建议在初始化时尝试设置它。

class MyClass {  
    public MyClass(Action<int> myMethod)
    {
        this.MyMethod = myMethod ?? x => { };
    }

    public readonly Action<int> MyMethod;
}

然而,如果接口未指定lambda属性,则无法实现具有MyMethod声明的接口。

F#具有对象表达式,允许您使用lambda组合对象。我希望在某个时候这也能成为c#的一部分。


0
你可以编写这段代码:
MyClass myObj = new MyClass();
myObj.TheAction = x => Console.WriteLine(x);
myObj.DoAction(3);

如果你用以下方式定义 MyClass:
class MyClass
{
  public Action<int> TheAction {get;set;}

  public void DoAction(int x)
  {
    if (TheAction != null)
    {
      TheAction(x);
    }
  }
}

但这应该不会太让人惊讶。


0

虽然不能直接实现,但是通过一些代码可以做到。

public class MyBase
{
    public virtual int Convert(string s)
    {
        return System.Convert.ToInt32(s);
    }
}

public class Derived : MyBase
{
    public Func<string, int> ConvertFunc { get; set; }

    public override int Convert(string s)
    {
        if (ConvertFunc != null)
            return ConvertFunc(s);

        return base.Convert(s);
    }
}

那么你就可以有代码了

Derived d = new Derived();
int resultBase = d.Convert("1234");
d.ConvertFunc = (o) => { return -1 * Convert.ToInt32(o); };
int resultCustom = d.Convert("1234");

我不会把ConvertFunc作为公共属性。上面的代码仅供参考。 - Robert Paulson

0
根据您想要做什么,解决这个问题有很多方法。一个好的起点是创建一个可获取和可设置的代理属性(例如 Action)。然后您可以编写一个方法来委托该操作属性,或者在客户端代码中直接调用它。这将打开许多其他选项,例如使操作属性私有可设置(可能提供构造函数来设置它)等。
例如:
class Program
{
    static void Main(string[] args)
    {
        Foo myfoo = new Foo();
        myfoo.MethodCall();

        myfoo.DelegateAction = () => Console.WriteLine("Do something.");
        myfoo.MethodCall();
        myfoo.DelegateAction();
    }
}

public class Foo
{
    public void MethodCall()
    {
        if (this.DelegateAction != null)
        {
            this.DelegateAction();
        }
    }

    public Action DelegateAction { get; set; }
}

0

不可以,方法不能像变量一样使用。

如果你在使用JavaScript,那么是的,你可以这样做。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接