创建实用程序类? [英] Creating a Utilities Class?
问题描述
我对OOP还是很陌生,并且在使用良好的编码原则的同时,尽我最大的努力使内容严格基于类.
I'm very new to OOP and am trying my hardest to keep things strictly class based, while using good coding principles.
我现在很公平地进入我的项目,并且我想将许多通用方法放入实用程序类中.是否有创建实用程序类的最佳方法?
I'm a fair ways into my project now and I have a lot of general use methods I want to put into an utilities class. Is there a best way to create a utilities class?
public class Utilities
{
int test;
public Utilities()
{
}
public int sum(int number1, int number2)
{
test = number1 + number2;
}
return test;
}
创建此Utilities类之后,是否仅创建一个Utilities对象并运行我选择的方法?我对这个实用程序类的想法正确吗?
After creating this Utilities class, do I just create an Utilities object, and run the methods of my choosing? Do I have this Utilities class idea correct?
推荐答案
您应将其设置为static
类,如下所示:
You should make it a static
class, like this:
public static class Utilities {
public static int Sum(int number1, int number2) {
return number1 + number2;
}
}
int three = Utilities.Sum(1, 2);
该类(通常)不应具有任何字段或属性. (除非您希望在代码中共享某个对象的单个实例,否则可以将static
设置为只读属性.
The class should (usually) not have any fields or properties. (Unless you want to share a single instance of some object across your code, in which case you can make a static
read-only property.
这篇关于创建实用程序类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!