【问题标题】:c# how to call an Action from generic extension method in another classc#如何从另一个类中的通用扩展方法调用Action
【发布时间】:2021-08-14 09:26:48
【问题描述】:

我正在尝试编写一个函数库,供我项目中的所有类使用(一个小的统一游戏)。这个问题可能已经被问过了,但我不确定要搜索什么并且还没有找到任何东西,所以我在这里。 我想在一个库中创建一个函数,该函数接受一个委托(或者至少是一个 Action 类型的对象,不确定这是否真的称为委托)并运行它。关键是,这个 Action 必须由另一个类型的对象调用并可能修改它(这意味着它必须由另一个对象调用)。我正在考虑为此使用通用扩展方法。 这是我现在拥有的一些代码(虽然这段代码不起作用,但它应该非常明确):

    public static class Library 
{
    public static void doStuffandCallMethod<T>(this T self, Action methodToExecute) {
        //DoStuff
        self.methodToExecute();

    }
    
}

这是我概括这段代码的尝试:

public static void WaitAndDo( Action methodToExecute) {
        //DoSuff();
        methodToExecute();
    }

效果很好。 但是编译器不理解,而是在类T中寻找一个名为methodToExecute的方法,而不是用参数(Action)methodToExecute描述的方法来替换它。 我应该如何从类 Lib 中将此 Action 称为对象 self?

非常感谢那些花时间处理它的人;)

编辑:这是一个最小的例子:

public class myObject {
    int number;

    public myObject() {
        number = 0;
    }

    public void method1() {
        Console.WriteLine("Bob is a great guy");
    }
    public void method2() {
        number++;
    }

    public void method3() {
        DoItForMe<myObject>(method2);
    }
}

public class Lib {
    public static void DoItForMe<T>(this T self, Action methodToExecute) {
        self.methodtoExecute();
    }
}

然后从主:

myObject bob = new myObject();
bob.method3();
Console.WriteLine("bob's number is" + bob.number);

应该给出输出

鲍勃的号码是 1

【问题讨论】:

  • 你能说明你想如何使用doStuffandCallMethod吗?
  • minimal reproducible example 可以更轻松地为您提供帮助。
  • 我添加了一个例子:)
  • 顺便说一句,如果示例遵循该语言的惯用命名约定,这将非常有帮助 - 这样就不会分散注意力。
  • 目前尚不清楚为什么这是一个扩展方法...但是您的示例代码只有四处错误:1)您有一个错字:您的参数称为methodToExecute但您试图将其调用为methodtoExecute; 2)扩展方法必须在静态类中; 3)您需要显式调用“this”上的扩展方法,例如this.DoItForMe&lt;myObject&gt;(method2);; 4) 你应该删除self. 部分。

标签: c# generics delegates


【解决方案1】:

methodToExecute 必须在没有 self 的情况下调用,因为这个方法是一个参数,而不是 self 的方法。

public static class Library
{
    public static void DoStuffandCallMethod<T>(this T self, Action methodToExecute)
    {
        //DoStuff
        methodToExecute();
    }
}

DoStuffandCallMethod 是您的实例的扩展方法,您可以使用 this 调用它:

public class MyObject
{
    private int number;
    public int Number => number;   // if you want to access from outside.
    // ...

    public void Method2()
    {
        number++;
    }

    public void Method3()
    {
        this.DoStuffandCallMethod(Method2);
    }
}

您正在扩展每种类型。您可以从 int 调用 DoStuffandCallMethod,...我觉得对于您的问题,接口比扩展方法更好。

【讨论】:

    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    相关资源
    最近更新 更多