简体   繁体   English

将方法作为带有参数的委托转发

[英]Forward a method as a delegate with arguments

I have the following problem. 我有以下问题。

class A
{
    public bool Execute(int a);
}

class B
{
    public bool Execute(bool a);
}


static class Consumer
{
    public bool Validate(Delegate d);
}

I would like to to be able to Call the Consumer's Validate method from inside the "A" and "B" Classes with the execute method as an argument 我希望能够以execute方法作为参数从“ A”和“ B”类内部调用使用者的Validate方法

Inside A or B : 在A或B内部:

public static main()
{
    x = new A()
    x1 = A.Execute(1);

    y = new B()
    y1 = B.Execute(true)

    Consumer.Validate(x1)
    Consumer.Validate(y1)
}

Of course this could work, but it would not do what I want it to. 当然这可以工作,但它并不能满足我的要求。 It would Execute and create a bool value X1 and not store it as a delegete to be executed at a certain point I Choose or to stre it as as internal object ia collection and then reExecute it. 它会执行并创建一个布尔值X1,而不将其存储为要在我选择的某个特定时刻执行的Delegete,或者将其作为内部对象ia集合然后再执行。

I hope I got it over to you so you can understand my intentions. 希望我能将它交给您,以便您了解我的意图。

But how to forward it with the argumets. 但是,如何将其与实物一起转发。

This is simplified explanation of the problem, but still the same. 这是问题的简化说明,但仍然相同。

Is it possible to pack the arguments with the methods delegate in the consumer, and then just execute them. 是否可以将参数与使用方的方法委托包装在一起,然后执行它们。

You could use lambda 您可以使用lambda

public bool Execute(int a)
{
    Consumer.Validate(() => this.Execute(a));
}

The lambda () => this.Execute(a) will store the value of a inside itself and provide to Validate simple you-should-know-nothing interface. 拉姆达() => this.Execute(a)将存储的值a内部本身并提供验证简单,你-应知全无接口。

And better change the signature of Validate to: 并且最好将Validate的签名更改为:

 public bool Validate(Func<bool> paramLessPredicate);

I think you need both delegate and value as arguments in the Consumer.Validate function: 我认为您需要在Consumer.Validate函数中同时使用委托和值作为参数:

public bool Validate<T>(Funct<T,bool> validator, T value)
{
    bool validatorResult = validator(value);
    // Do whatever..
    return someBool;
}

And in A: 并在A:

int value = 10;
bool result = Consumer.Validate(Execute, value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM