C#全局变量访问 [英] C# Global Variables Accessing

查看:98
本文介绍了C#全局变量访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类,因为它有一个全局变量。



I have created a class as the following it has one global variable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LankaLab
{
    class dbConnect
    {

        public String strSuperPatID;

        public String StrSuperPatID
        {
            get { return strSuperPatID; }
            set { strSuperPatID = value; }
        }

                     
         }
}





现在我有创建了另一个类,我创建了一个dbConnect类的实例。





Now I have created another class and I have created an instance of the dbConnect class.

 public partial class frmFulBldCuntDet : Form
{

  private dbConnect dbConn = new dbConnect();

 }





现在我想在dbConnect类中为全局变量设置值来自frmBldCuntDet类。我已经创建了getter()& setter()方法。但是现在我想从frmBldCuntDet向strSuperPatID添加值并从另一个类显示它(还没有创建)。我只需要使用getter()& setter(0方法。



谢谢!



从OP移动回答问题解决方案 - OriginalGriff



frmBldCuntDet类具有以下变量,用于生成自动患者ID。







Now I want to set values to the global variable in the dbConnect class from the frmBldCuntDet class. I already created the getter() & setter() methods. But now I want to add values to the strSuperPatID from the frmBldCuntDet and display it from another class ( haven''t created yet). All I need is to use getter() & setter(0 methods.

Thank You!

Moved to question from OP "solution" - OriginalGriff

frmBldCuntDet class has the following variables and those use to generate a automatic patient id.


 Class - 01
            
            public partial class frmFulBldCuntDet : Form
    {
            private dbConnect dbConn = new dbConnect();

            private String strID;
            private String strPatID;

            private int intYear;
            private String strYear;

            private int intMonth;
            private String strMonth;

         private void btnPrint_Click(object sender, EventArgs e)
        {
            intYear = DateTime.Now.Year;
            strYear = intYear.ToString();
            intMonth = DateTime.Now.Month;
            strID = cmbPatID.Text;

//MyMethod() in use.
            MyMethod();

      frmHBAIC HbIAC01 = new frmHBAIC();

      HbIAC01.show(); 

       }
         /* This MyMethod will pass the value of strPatID to the global variable StrSuperPatID */
           private string MyMethod() {

            return(dbConn.StrSuperPatID = strPatID);
        
        }

    }

 Class - 02

  public partial class frmHBAIC : Form
    {

     private dbConnect dbConn = new dbConnect();

   /* When the button1 is clicked I want to display the value of StrSuperPatID (global variable) in a messagebox.*/
   // I tried this as the follwoing but it didn't happen!
      private void button1_Click(object sender, EventArgs e)
        {
          MessageBox.show(dbConn.StrSuperPatID);  
        }

    }

  Class - 03 - This class includes the global variables and getter & setter metohds of its'.

  class dbConnect
    {

        public String strSuperPatID;

        public String StrSuperPatID
        {
            get { return strSuperPatID; }
            set { strSuperPatID = value; }
        }

                     
         }





我找不到阻止将值传递给全局变量的问题。



希望你能帮助我



谢谢!



I cannot find the problem yet that preventing passing the values to the global variable.

Hope that you will help me

Thank You!

推荐答案

首先,不要暴露你的支持领域!

要么使用自动属性:

First off, don''t expose your backing fields!
Either use an automatic property:
public String StrSuperPatID { get; set; }

或将支持字段声明为 private

or declare the backing field as private

class dbConnect
{

    private String strSuperPatID;

    public String StrSuperPatID
    {
        get { return strSuperPatID; }
        set { strSuperPatID = value; }
    }

要使用类实例的getter和setter很简单:



To use the getter and setter of the class instance is easy:

public partial class frmFulBldCuntDet : Form
   {
   private dbConnect dbConn = new dbConnect();
   private void MyMethod()
      {
      dbConnect.StrSuperPatID = "Hello World!";    // Uses the setter
      ...
      Console.WriteLine(dbConnect.StrSuperPatID);  // Uses the getter
      }
   }





我没有帮助我解决这个问题。但是我把修改后的问题作为解决方案02,并希望它能描述我的问题



你知道C#没有全局变量吗?一切都包含在一个类中?因此,如果您想从不同的类访问StrSuperPatID,您需要通过如上所示的类实例访问它们,或者在dbConnect类中使它们成为 static





"It didn''t help me to solve the problem. However I have placed the modified question as the solution 02 and hope it will describe my problem"

You are aware that C# doesn''t have global variables? That everything is contained within a class? So if you want to access StrSuperPatID from a different class, you either need to access them via a class instance as shown above or make them static within the dbConnect class:

class dbConnect
    {
    private static String strSuperPatID;
    public static String StrSuperPatID
        {
        get { return strSuperPatID; }
        set { strSuperPatID = value; }
        }
    }

当我说不要暴露你的支持领域!为什么你继续做所以?如果外面的世界可以直接修改后备商店,它就会破坏拥有房产的目的!



你提到过 不要暴露你的支持领域!这确实让人觉得这是关于封装的吗?或者其他什么?你能解释一下吗?



是的,它是关于封装的!

当你声明一个属性时,你实际上是在声明两个方法:getter和setter。

And when I said "don''t expose your backing fields!" why did you continue to do so? It defeats the purpose of having a property in the first place if the outside world can just modify the backing store directly!

"You have mentioned that "don''t expose your backing fields!" does make it any sense that this is about encapsulation? Or other thing? can you explain it to me?"

Yes, it is about encapsulation!
When you declare a property, you are actually declaring two methods: the getter and the setter.

string myString;
public string MyString
    {
    get { return myString; }
    set { myString = value; }
    }

相当于:

Is the equivalent of:

string myString;
public string GetMyString() { return myString; }
public void SetMyString(string value) { myString = value; }



编译器添加一些语法糖以使它们更易于使用:


The compiler adds some syntactic sugar to make them easier to use:

MyString = "hello";
Console.WriteLine(MyString);

而不是必须写:

Instead of having to write:

SetMyString("hello");
Console.WriteLine(GetMyString());

并且属性看起来像普通变量,但它们添加了验证数据,将其放入控件进行显示或使用完全不同的功能的功能相反 - 所有没有用户知道它。



当你暴露你的支持领域(这只是给予类级别变量的名称,你实际存储属性值为: myString 在我给出的示例中,以及公开它意味着通过制作使其在课外可用它是 public ,你让用户完全绕过机制。如果您的属性设置器验证字符串,以便它始终是正确且有效的UserName,那么暴露支持字段可让外部世界绕过该验证并将值更改为无效的UserName,而无需您的类知道它。所以你的程序会因为你的其他代码依赖于验证而确保它不需要在每次使用它时检查它。



所以如果你声明 strSuperPatID StrSuperPatID public 然后没有因为你班外的世界并不需要使用它,所以首先要考虑这个属性。



建立你的支持领域私人并且外面的世界不能触摸它们,除非通过您控制发生的事情的财产! :笑:





好的朋友那我该怎么办?请说出最佳做法!谢谢! / b>



要么你需要公共变量是静态的(然后它有一个实例,通过类名而不是变量访问)或你想要的父(form1)做的工作。就个人而言,在大多数情况下,我会选择父级,但在这种特定情况下,我会将CommonVariable类设置为静态并使用自动属性(因为除了存储值之外你不做任何其他操作)。

And properties look like "normal" variables, but they add the capability to validate data, put it into controls for display, or use something totally different instead - all without the user knowing about it.

When you expose your backing field (and that is just the name given to the class level variable you actually store the property value in: myString in the example I gave, and to expose it means to make it available outside the class by making it public for example) you let the user circumvent the mechanism altogether. If your property setter validates a string so that is it always a correct and valid UserName for example, then exposing the backing field lets the outside world bypass that validation and change the value to an invalid UserName without your class knowing about it. So you program falls over because your other code relies on the validation to ensure it doesn''t need to check the value every time it uses it.

So if you declare both strSuperPatID and StrSuperPatIDas public then there is no point in having the property in the first place because the world outside your class doesn''t have to use it.

Make your backing fields private and the outside world can''t touch ''em except via the property where you control what happens! :laugh:


"Ok pal then what should I do? Please state the best practice! Thank You!"

Either you need the common variables to be static (and then it has a single instance, accessed via the class name rather than a variable) or you want the Parent (form1) do do the work. Personally, I would go with the parent in most cases, but in this specific case I would make the CommonVariable class static and use an automatic property (since you do nothing else with it than store the value).

public static class CommonVariables
    {
    public static string StrSuperPatID {get; set;}
    }



然后您可以通过班级名称访问它。

Form1:


You then access it via the class name.
Form1:

private void button1_Click(object sender, EventArgs e)
    {
    CommonVariables.StrSuperPatID = strYear + strMonth + strID;
    frmHBAIC hbi01 = new frmHBAIC();
    hbi01.Show();
    }



和Form2:


and Form2:

private void button1_Click_1(object sender, EventArgs e)
    {
    label1.Text = CommonVariables.StrSuperPatID;
    }

不尝试以任何一种形式声明CommonVariables类的变量。

Without trying to declare a variable of the class CommonVariables in either form.


这篇关于C#全局变量访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆