Share a variable between two classes

半城伤御伤魂 提交于 2020-01-30 13:27:43

问题


I have two different .cs windows in just 1 project. Each one runs a different part of my program. But now I need to use a variable (i) of mainwindow.cs in Form.cs. This variable changes all the time. How can I do it?

MAINWINDOW.CS

   namespace samples
   {
     using System.IO;
     ........
     public partial class MainWindow : Window
       {
       float i;     
       }
    }   

FORM1.CS

    namespace samples
    {
    public partial class Form1 : Form
    {
        public Form1()
        {
        InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        ....
        chart1.Series["Pakistan"].Points.AddXY(i, j);
        }
    }
    }

回答1:


If you declare your variable without an access modifier as you have done, it is implicitly private and thus only accessible within the class where it is declared (MainWindow in this case). You can add an access modifier:

internal float i;

This will allow you to access i from other classes within your assembly, like Form1.

See MSDN for more information on access modifiers: https://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx

You should almost never expose fields like i outside of a class, though; instead what you want to do is use a property:

private float i;

public float I
{
    get { return i; }
    set { i = value; }
}

Better yet, you could make use of an auto-implemented property so you don't even need to have a backing field (i):

public float I { get; set; }

There are many reasons why exposing properties rather than fields is better. Here is one source on the topic (it's centered around VB, but the theories should be the same).

Addendum: please consider proper naming conventions for variables. i is not a good name for your variable.




回答2:


your default access modifier is private if you don't mention it . Make it public

public float i {get; set;}  


来源:https://stackoverflow.com/questions/28881368/share-a-variable-between-two-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!