简体   繁体   English

如果我只有一个静态变量的类-我应该将此类声明为静态的吗?

[英]In case i have class with only one static variable - should i declare this class as static?

This is my class how hold my last visited Path: 这是我的课程如何保持我上次访问的路径:

public class LastPath
{
    private static string _lastPath;

    public static string lastPath
    {
        get { return _lastPath; }
        set { _lastPath = value; }
    }
}

I would say you to do this: 我会说你这样做:

public static class LastPath
{
    public static string lastPath
    {
       get;set;
    }
}

You should declare it as static as static classes cannot be instantiated, while non static classes can be instantiated, which is not needed. 您应将其声明为static因为无法实例化静态类,而可以实例化非静态类,这是不需要的。

make the class static and make a public property as static and you are done, like this: 将类设为静态,并将公共属性设为静态,就可以完成操作,如下所示:

public static class LastPath
{

    public static string lastPath { get;set;}

}

If all members of a class is static and your class is not meant to instantiated it should be static . 如果一个类的所有成员都是静态的,并且您的类不是要实例化的,则它应该是static

In this case your class satisfies the above rule or guideline so marking it as static will make sense because you don't have any instance member. 在这种情况下,您的类满足上述规则或准则,因此将其标记为static将是有意义的,因为您没有任何实例成员。

LastPath path = new LastPath();
path.????//  Nothing to access, so prevent instantiation by marking class static.

Being said that If you have only one field in your class and no methods I'd argue that you probably don't need a class at all, just refactor it to some other class where it would make sense. 有人说,如果您的类中只有一个字段并且没有方法,那么我会认为您可能根本不需要一个类,只需将其重构为其他有意义的类即可。

First - it looks odd to me to create class for holding single variable. 首先-创建用于保存单个变量的类对我来说似乎很奇怪。 Consider to use simple string variable lastVisitedPath instead. 考虑使用简单的字符串变量lastVisitedPath代替。 If you use this variable in single class, then make it field of that class. 如果在单个类中使用此变量,则使其成为该类的字段。

Second - naming is not very readable. 第二-命名不是很可读。 Here is how getting last path looks like: LastPath.lastPath . 这是获取最后一条路径的样子: LastPath.lastPath You see this useless duplication? 您看到这个无用的重复吗? Also keep in mind, that due to Microsoft naming guidelines public members should have Pascal Case names. 还请记住,由于Microsoft的命名准则,公共成员应具有Pascal Case名称。 Consider to create class with descriptive name like GlobalValues or Cache which reflects its purpose: 考虑创建具有描述性名称的类,例如GlobalValuesCache ,以反映其用途:

public static class GlobalValues // holds values which are globally accessible
{
   public static string LastVisitedPath;
   // other global values
}

So that usage will look like GlobalValues.LastVisitedPath or Cache.LastVisitedPath . 这样的用法将类似于GlobalValues.LastVisitedPathCache.LastVisitedPath Of course, if these classes don't supposed to be instantiated, they should be static. 当然,如果不应该实例化这些类,则它们应该是静态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM