为什么可以在WCF服务中公开显示私有方法?

bil*_*lal 4 c# wcf .net-4.5

为什么我们可以将[ OperationContract]属性放在wcf服务中的私有方法上.从我编程的一天开始,我就被教导私人方法是那些在课外无法访问的方法.现在,在WCF服务中,您可以公开公开私有方法.

    [ServiceContract]
    public class MyServices
    {
        [OperationContract]
        private int add(int a,int b)
        {
            return a + b;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Rob*_*evy 6

不确定为什么它是这样设计的,但是如果你检查一下,第336行说

internal const BindingFlags ServiceModelBindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;

特别注意NonPublic标志.然后,当WCF使用反射来确定要公开的方法时,这将在后面的第678行中使用:

   static List<MethodInfo> GetMethodsInternal(Type interfaceType)
   {
            List<MethodInfo> methods = new List<MethodInfo>();
            foreach (MethodInfo mi in interfaceType.GetMethods(ServiceModelBindingFlags))
            {
                if (GetSingleAttribute<OperationContractAttribute>(mi) != null)
                {
                    methods.Add(mi);
                }
                ...
Run Code Online (Sandbox Code Playgroud)

我同意你这是一个奇怪的决定,但WCF开发人员明确决定通过包含NonPublic标志来做到这一点.

http://referencesource.microsoft.com/#System.ServiceModel/System/ServiceModel/Description/ServiceReflector.cs,c1358e6f97071bfa