C#使用返回变量而不是全局变量

本文关键字:全局变量 变量 返回 | 更新日期: 2023-09-27 18:28:33

请注意,我正在使用Visual Studio 2015创建Excel VSTO。我有一大堆关于全局变量的问题。在大多数情况下,我一直在努力避免它们(因为"全局变量很糟糕"),但同样,我也看到人们说,如果你正确使用全局变量,使用全局变量也不错。

假设以下类别结构-

 1    public class ribbon {  //Class containing Ribbon button to activate
 2        private void button_click(){
 3            Globals.ThisAddIn.openUI();
 4        }
 5    }
 6    
 7    public class formClass {  //Class containing the user  form that will be used
 8        private void button_click(){
 9            Globals.ThisAddIn.setProperties(this.field1.Value, this.field2.Value);
10            Globals.ThisAddIn.runFunction();
11        }
12    }
13    
14    public class ThisAddIn {
15        struct someProperties {
16            public string foo;
17            public string bar;
18        }
19    
20        someProperties ps = new someProperties();
21        formClass ui = new formClass();
22    
23        public void openUI(){
24            ui.showDialog();
25        }
26    
27        public void setProperties(string field1, string field2){
28            ps.foo = field1;
29            ps.bar = field2;
30        }
31    
32        public void runFunction(){
33            doSomethingWith ps
34        }
35    }

关于上述结构的问题-

  1. 乍一看,在这种情况下使用全局变量是否"不恰当"?全局变量的"正确"用法是什么
  2. 第9行-如果我要更改表单,使field1&字段2是公共的并且改为调用Gloabls.ThisAddIn.setProperties()并且在线路28+29上说ps.foo = ui.field1.Value;&ps.bar = ui.field2.Value;-这会被视为"不良做法"吗?这种语法在什么情况下适用
  3. 第10行&线路27&32-我想改变结构,让setProperties函数返回someProperties结构,而不是将其作为全局变量,然后使用该返回值传递给runFunction(),如下所示:

Globals.ThisAddIn.runFunction(globals.ThisAddIn.setProperties(foo, bar));
public someProperties setProperties(string field1, string field2) {
    someProperties ps = new someProperties();
    ps.foo = field1;
    ps.bar = field2;
    return ps;
}
public void runFunction(someProperties ps){
    doSomethingWith ps;
}

这个结构比我现在的更好吗?如果是这样的话,为什么在这种情况下使用全局变量是"糟糕的"呢?

C#使用返回变量而不是全局变量

  1. 正确使用全局变量的主要时间是如果它们是常数,从而消除函数更改其值的危害,并且无法找到更改发生的位置。

  2. 如果要将它们公开,将被视为不好的做法,第一个原因是它们应该是属性,而不是公共字段。我会直接避开字段,以进一步保留封装。

  3. 这似乎是一个更好的选择,尽管我仍然相信有一种更实用的方法可以在没有全局变量的情况下获得这种影响,也可以增加封装。

编辑:

在不太了解你的程序的情况下,也许会有这样的事情:

public static class ThisAddInManager
{
    struct someProperties
    {
        public string foo, bar;
    }
    public static var SomeProperties { private get; set; } = new someProperties();
    public static var UI { private get; set; } = new formClass();
    public static void OpenUI() => UI.showDialog();
    public static void RunFunction() => doSomethingWith(SomeProperties);   
}

您可以在这里了解更多关于属性的信息