我正在编写一个类,理想情况下应该具有相同签名的多个方法。如果所有类都遵循相同的签名,是否可以强迫类检查其方法?

如果可以在编译时/构建期间进行检查,那将是理想的

如果您认为签名为int <methodName>(string, int, char)

public class Conditions {
        // no error
        int MethodA(string a, int b, char c)
        {
            return 0;
        }
        // no error
        int MethodB(string a, int b, char c)
        {
            return 1;
        }

        // should throw error because return type does not match signature
        string MethodC(string a, int b, char c)
        {
            return "Should throw an error for this function";
        }
    }
}

最佳答案

这有点作弊,但是如果您要求开发人员注册他们的方法,则可以通过要求方法与委托匹配来强制编译时错误。

本质上,这就是事件处理程序和回调的工作方式。

namespace Framework
{
    public delegate int MyApiSignature(int a, string b, char c);

    public class Core
    {
        static public void RegisterMethod(MyApiSignature method)
        {
            //Doesn't even have to actually do anything
        }
    }
}


namespace Custom
{
    using Framework;

    class Foo
    {
        public Foo()
        {
            Core.RegisterMethod(MethodA);  //Works
            Core.RegisterMethod(MethodB);  //Compile-time error
        }

        public int MethodA(int a, string b, char c)
        {
            return 0;
        }

        public int MethodB(int a, string b, byte c)
        {
            return 0;
        }
    }
}

10-07 19:17
查看更多