创建实用程序类?

soo*_*ise 20 c# oop utilities class

我是OOP的新手,我正在尽最大努力保持严格基于类的东西,同时使用良好的编码原则.

我现在是一个很好的方式进入我的项目,我有很多一般使用方法,我想放入实用程序类.有没有最好的方法来创建实用程序类?

public class Utilities
{
    int test;

    public Utilities()
    {
    }

    public int sum(int number1, int number2)
    {
        test = number1 + number2;
    }
    return test;
}
Run Code Online (Sandbox Code Playgroud)

创建此Utilities类后,我是否只创建一个Utilities对象,并运行我选择的方法?我有这个公用事业课程的想法是否正确?

SLa*_*aks 37

你应该把它变成一个static类,像这样:

public static class Utilities {
    public static int Sum(int number1, int number2) {
        return number1 + number2;
    }
}

int three = Utilities.Sum(1, 2);
Run Code Online (Sandbox Code Playgroud)

该类应该(通常)没有任何字段或属性.(除非您想在代码中共享某个对象的单个实例,在这种情况下,您可以创建static只读属性.

  • 只要它有意义,您就可以编写扩展方法.对于扩展方法,可以参考http://msdn.microsoft.com/en-us/library/bb383977.aspx (4认同)

Lan*_*nce 13

如果您使用的是.NET 3.0或更高版本,则应该查看扩展方法.它们允许你写一个static将充当针对特定的类型,比如功能Int32,看上去似乎是一个方法那个对象.那么你可以:int result = 1.Add(2);.

试试这个; 它可能只是向你展示另一种方式.;)

C#教程 - 扩展方法