[英]Should I use static fields or private using an instance of the class to access
I am accessing fields of a class and if I use them as static I can use them from the class without creating an instance of the class which means less code. 我正在访问一个类的字段,如果我将它们用作静态字段,则可以从类中使用它们,而无需创建该类的实例,这意味着更少的代码。 But should I?
但是我应该吗? What is the best practice?
最佳做法是什么?
public class myClass
{
private static DataSet myDS;
myClass.myDS = new DataSet();
}
or 要么
private DataSet myDS;
public DataSet MyDS
{
get { return myDS; }
set { myDS = value; }
}
myClass a = new myClass();
a.MyDS = new DataSet();
It all depends on how you want to use the members of your class and how you want control access to those members. 这完全取决于您要如何使用类的成员以及您希望如何控制对这些成员的访问。 It has nothing to do with writing less code.
它与编写更少的代码无关。 In the example you provided if you wanted to use the same DataSet across all instances of "myClass", or across the your application if the property were public/internal, then make it static.
在示例中,您提供了是否要在“ myClass”的所有实例之间使用相同的数据集,或者如果属性是公共/内部的,则在整个应用程序中使用相同的数据集,则将其设为静态。 If you require a new DataSet each time you create an instance of "myClass", then make it non-static.
如果每次创建“ myClass”的实例时都需要一个新的DataSet,则使其成为非静态的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.