本文介绍了C#将类作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an Interface, that has some methods

interface IFunction
{
    public double y(double x);

    public double yDerivative(double x);
}

并且我已经实现了 static 类.

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

    public static double yDerivative(double x)
    {
        return 0;
    }
}

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

I want to pass this classes as a parameter to another function.

 AnotherClass.callSomeFunction(TemplateFunction);

以及其他捕获请求的类

class AnotherClass
{
    IFunction function;
    public void callSomeFunction(IFunction function)
    {
        this.fuction = function;
    }
}

好吧,它行不通...我尝试使用Type表达式,但这似乎打破了使用接口的想法.是否有人知道如何更正代码?

Well, it doesn't work... I've tried to use the Type expression, but that seams to break the idea of using an interface. Does anyone have an idea, how to correct the code?

推荐答案

静态类无法实现接口,但是您可以通过使类成为非静态类和泛型方法来轻松地克服这一点:

Static classes can't implement interfaces, but you can easily overcome this by making your class non static and a generic method:

class AnotherClass
{
    IFunction function;

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

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

This is much close to the syntax you wanted:

AnotherClass.callSomeFunction<TemplateFunction>();

但是我实际上认为这种方法太复杂并且可能使某人感到困惑,您应该遵循Servy的方法,该方法更简单:

But I actually think that this way is too complicated and likely to confuse someone, you should follow Servy's approach which is way simpler:

AnotherClass.callSomeFunction(TemplateFunction.Instance);

这篇关于C#将类作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:46