有没有一种方法可以限制C#类中的函数仅使用特定签名?

时间:2019-04-03 07:24:29

标签: c# compile-time

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

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

如果您认为签名为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";
        }
    }
}

3 个答案:

答案 0 :(得分:3)

您可以进行单元测试:

    [TestMethod]
    public void Conditions_MethodsHaveCorrectSignature()
    {
        var whitelist = new List<string> { "Finalize", "MemberwiseClone" };
        var t = typeof(Conditions);
        var m = t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);

        foreach (var item in m.Where(x => !whitelist.Contains(x.Name)))
        {
            Assert.AreEqual(typeof(int), item.ReturnType);

            CollectionAssert.AreEquivalent(new List<Type> { typeof(string), typeof(int), typeof(char) },
                item.GetParameters().Select(x => x.ParameterType).ToList());
        }
    }

答案 1 :(得分:3)

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

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

foo()

答案 2 :(得分:2)

不直接。您可以使用Roslyn为其编写分析器,也可以编写通过反射检查签名的单元测试。