Is there a single way to call Invoke () in C #?

The next test passes, but I wonder if a unified treatment is possible. It can be done?

public abstract class MyInvokable<TResult> {
  public abstract TResult Invoke();
}
public class IntInvokable: MyInvokable<int> {
  public override int Invoke() {
    return 12;
  }
}
[Test()]
public void FunctionInvokeTest () {
  Func<int> foo = () => 6;
  IntInvokable bar = new IntInvokable();
  int six = foo.Invoke();
  int twelve = bar.Invoke();
  Assert.AreEqual(6, six);
  Assert.AreEqual(12, twelve);
  /* Now, what I really want to do but can't, as far as I can tell:
  List<SomeType> list = new List<SomeType>(){foo, bar};
  Assert.AreEqual(6, list[0].Invoke());
  Assert.AreEqual(12, list[1].Invoke()); */
}

EDIT: a function request was launched from Microsoft here: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/10185579-create-an-iinvokable-t-interface

+4
source share
2 answers

C # does not allow anything even remotely close to this type of dynamic behavior.

But you need to go this route, you can always use it dynamic, basically signaling to the compiler that all bets are disabled. This will work:

 List<dynamic> list = new List<dynamic>(){foo, bar};
 Assert.AreEqual(6, list[0].Invoke());
 Assert.AreEqual(12, list[1].Invoke());

- , , list, Invoke.

, , TypeScript - , /, , , . # , , , , .

- #, AFAIK.

+2

List<T>, , , , T Invoke, , .

, :

public interface IInvokable
{
    int Invoke();
}

var l = new List<IInvokable>();

:

public class Invokable
{
    public virtual int Invoke() { ... }
}

var l = new List<Invokable>();

, , , :

public class FuncInvokable : IInvokable
{
    private readonly Func<int> _Func;
    public FuncInvokable(Func<int> func) { _Func = func; }
    public int Invoke() { return _Func(); }
}

... :

var l = new List<Func<int>>();
l.Add(foo);
l.Add(() => bar.Invoke());

:

var l = new List<Type that has an Invoke method>();
+2

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


All Articles