繁体   English   中英

c# 如何从另一个通用扩展方法调用操作 class

[英]c# how to call an Action from generic extension method in another class

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

    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();
    }

效果很好。 但是,编译器不理解并在 class T 中寻找一个名为 methodToExecute 的方法,而不是将其替换为参数(Action)methodToExecute 所描述的方法。 我应该如何将此操作称为 class Lib 中的 object 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);

应该给 output

鲍勃的号码是 1

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

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

DoStuffandCallMethod是您实例的扩展方法,您可以这样调用

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 ,...我觉得对于您的问题,接口是比扩展方法更好的方法。

暂无
暂无

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

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