Is it possible to overestimate a method using a lambda function

Is there a way to override a class method using a lambda function?

For example, with a class definition

class MyClass {  
    public virtual void MyMethod(int x) {
        throw new NotImplementedException();
    }
}

Anyway:

MyClass myObj = new MyClass();
myObj.MyMethod = (x) => { Console.WriteLine(x); };
+3
source share
6 answers

No. However, if you first declare the method as a lambda, you can set it, although I would try to do it during initialization.

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

    public readonly Action<int> MyMethod;
}

However, this cannot implement the interface declared by MyMethod, unless the interface specifies a lambda property.

F # has object expressions that allow you to compose an object from lambda. Hopefully at some point this is part of C #.

+5
source

Chris is right that methods cannot be used as variables. However, you can do something like this:

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

:

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

. .

JavaScript, , .

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");
0

, , .

(, Action), . , , . , , 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

Source: https://habr.com/ru/post/1712160/


All Articles