C#传递一个Class作为参数

Erm*_*tar 2 c# parameters methods interface class

我有一个接口,有一些方法

interface IFunction
{
    public double y(double x);

    public double yDerivative(double x);
}
Run Code Online (Sandbox Code Playgroud)

我有静态类,正在实现它.

static class TemplateFunction:IFunction
{
    public static double y(double x)
    {
        return 0;
    }

    public static double yDerivative(double x)
    {
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想将这些类作为参数传递给另一个函数.

 AnotherClass.callSomeFunction(TemplateFunction);
Run Code Online (Sandbox Code Playgroud)

以及其他一些捕获请求的类

class AnotherClass
{
    IFunction function;
    public void callSomeFunction(IFunction function)
    {
        this.fuction = function;
    }
}
Run Code Online (Sandbox Code Playgroud)

好吧,它不起作用......我试图使用Type表达式,但是接缝打破了使用接口的想法.有没有人有想法,如何纠正代码?

Bla*_*ear 5

静态类无法实现接口,但您可以通过使类非静态和通用方法轻松克服此问题:

class AnotherClass
{
    IFunction function;

    public void callSomeFunction<T>()
        where T: IFunction, new()
    {
        this.fuction = new T();
    }
}
Run Code Online (Sandbox Code Playgroud)

这非常接近您想要的语法:

AnotherClass.callSomeFunction<TemplateFunction>();
Run Code Online (Sandbox Code Playgroud)

但我实际上认为这种方式过于复杂,可能会使某些人感到困惑,你应该遵循Servy的方法,这种做法更为简单:

AnotherClass.callSomeFunction(TemplateFunction.Instance);
Run Code Online (Sandbox Code Playgroud)