是否可以对 C# 中的几种方法应用限制

Is it possible to apply restrictions to several methods in C#

我有一个脚本如下:

Int MethodOne (int param) {
    If (param > 5) {
        Return 0;
    }
    Return param;
}

Int MethodTwo (int param) {
    If (param > 5) {
        Return 0;
    }
    Return param * anotherVariable;
}

是否可以将条件 'method should not execute if param > 5' 应用于我的所有方法,而无需在每个方法中重写它?

我不知道如何做 OP 所要求的,所以这是我能想到的最佳答案。一种方法是创建另一个 Restriction() 方法,这样您就可以更改它一次,而不是在每个方法中都更改。

bool Restriction(int param)
{
    return param <= 5;
}

int MethodOne(int param)
{
    return Restriction(param) ? param : 0;
}

int MethodTwo(int param) 
{
    return Restriction(param) ? param * anotherVariable : 0;
}

您可以使用函数。

Func<int,int> restrict = x => x <= 5 ? x : 0;

int MethodOne (int param) {
    return restrict(param);
}
int MethodTwo (int param) {
    return restrict(param) * anotherVariable;
}
//...

当您执行 restrict(param) 时,它会为您进行检查并 return 所需的数字。

一种方法是不传递 int(参见 primitive obsession

public class NotMoreThanFive 
{
  public int Value {get; private set;}
  public NotMoreThanFive(int value) 
  {
    Value = value > 5 ? 0 : value;
  }
}

现在

Int MethodOne (NotMoreThanFive param) {
    Return param.Value;
}

Int MethodTwo (NotMoreThanFive param) {
    Return param.Value * anotherVariable;
}

与其编写多个方法,不如编写一个方法,该方法采用一个参数来决定它需要调用哪个功能,并将您的条件放在该方法的顶部:

Int MethodOne (int func, int param) {
    If (param > 5) {
        Return 0;
    }

    switch(func)
    {
        case 1: Return param; break;
        case 2: Return param * anotherVariable; break;
        ...
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication8
{
    class Program
    {
        delegate int restriction(int x, string methodName);

        static void Main(string[] args)
        {
            int x = MethodOne(6);
            Console.WriteLine(x);

            int x1 = MethodOne(4);
            Console.WriteLine(x1);

            int x2 = Methodtwo(6);
            Console.WriteLine(x2);

            int x3 = Methodtwo(4);
            Console.WriteLine(x3);



            Console.ReadLine();
        }

        public static int restrictionMethod(int param, string methodName)
        {
            if (param > 5)
            {
                param = 0;              

            }
            if (methodName == "MethodOne")
            {
                return param;
            }
            else if (methodName == "Methodtwo")
            {
                return param * 4;
            }

            return -1;
        }

        public static int MethodOne(int param) 
       {
           restriction rx = restrictionMethod;
           int returnValue = rx(param, "MethodOne");
           return returnValue;
       }

        public static int Methodtwo(int param)
       {
           restriction rx = restrictionMethod;
           int returnValue = rx(param, "Methodtwo");

           return returnValue;
       }


    }
}