简体   繁体   English

我应该使用静态字段还是使用类的实例进行私有访问

[英]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.

相关问题 在这种特定情况下,我应该使用静态类还是实例类? - Should I use a static or instance class in this specific case? 我应该使用静态字段并互锁吗? - Should I use static fields and interlocked together? 我应该使用公共属性和私有字段还是公共字段作为数据? - Should I use public properties and private fields or public fields for data? 我应该在C#类中使用私有字段,还是应该使用公共属性? - Should I use private fields in my C# class or public Properties are good enough? 我应该将我的私有类方法设为静态吗? - Should I make my private class methods static? 我应该使用静态类来存储数据吗? - Should I use static class for storing data? 如何从基类的实例创建派生类的实例并包含私有字段? - How can I create an instance of a derived class from an instance of a base class and include private fields? 如何清除通用静态类中的字段? - How should I clear fields in generic static class? 是否应将公共静态字段用于图像和颜色? - Should I use public static fields for images and colors? 如何在一个静态方法中锁定类的私有静态字段,然后在其他实例方法中释放它? - How can I lock a private static field of a class in one static method and then release it in some other instance method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM