从未知类型T执行功能

Som*_*son 0 c# function

我有一个这样的课:

public class TestClass
{
    public int A { get; set; }
    public int B { get; set; }
    //Other stuff...

    public static static int TestFunction(int c, int d)
    {
         //Other stuff...
         return c + d;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有很多不同的类,有不同的属性,但总是带有不同内容的"TestFunction"函数(如+/*/:/ - ).

现在我想构建另一个调用此函数的函数,而不知道函数的类型,但我知道"Testfunction"总是在那里.

这是我的尝试:

public static int AnotherFunction<T>(T inClass, int c, int d)
{
    //Other stuff...
    return inClass.TestFunction(c, d);
}
Run Code Online (Sandbox Code Playgroud)

这些函数仅用于显示目的(不要只是说"直接调用函数,因为它没有做太多").
问题是Visual Studio说"TestFunction"是未知的.
我怎么能不知道上课得到什么呢?

Ehs*_*jad 5

您可以创建一个接口,类型可以从中继承并为这些接口提供自己的实现.

然后,您可以为该接口类型上的泛型参数约束您的方法,以便从中继承的所有类型都可以调用相应的实现.

请参阅以下内容:

public interface IInterface
{
   int TestFunction(int c, int d);
}

public class TestClass : IInterface
{
    public int A { get; set; }
    public int B { get; set; }
    //Other stuff...

    public int TestFunction(int c, int d)
    {
         //Other stuff...
         return c + d;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以写一个像这样的方法:

public static int AnotherFunction<T>(T inClass, int c, int d) where T : IInterface
{
   //Other stuff...
   return inClass.TestFunction(c, d);
}
Run Code Online (Sandbox Code Playgroud)

希望它能给你一些想法.