有没有办法限制C#类中的函数只使用特定的签名?

问题描述 投票:2回答:3

我正在写一个理想情况下应该具有相同签名的多个方法的类。有没有办法强制类检查它的方法,如果它们都遵循相同的签名?

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

如果你认为签名是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";
        }
    }
}
c# compile-time
3个回答
3
投票

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

这实际上是事件处理程序和回调的工作方式。

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;
        }
    }
}

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());
        }
    }

2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.