在两个类之间共享一个变量 [英] Share a variable between two classes

查看:67
本文介绍了在两个类之间共享一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 1 个项目中有两个不同的 .cs 窗口.每个都运行我的程序的不同部分.但是现在我需要在 Form.cs 中使用 mainwindow.cs 的变量 (i).这个变量一直在变化.我该怎么做?

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?

主窗口.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);
        }
    }
    }

推荐答案

如果你像你所做的那样在没有访问修饰符的情况下声明你的变量,它是隐式的private,因此只能在类中访问它被声明(在本例中为 MainWindow).您可以添加访问修饰符:

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;

这将允许您从程序集中的其他类访问 i,例如 Form1.

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

有关访问修饰符的更多信息,请参阅 MSDN:https://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx

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

不过,您几乎不应该在类之外暴露像 i 这样的字段;相反,您想要做的是使用属性:

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; }
}

更好的是,您可以使用自动实现的属性,这样您甚至不需要支持字段 (i):

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; }

显示属性而不是字段更好的原因有很多.这是该主题的一个来源(它以 VB 为中心,但理论应该是相同的).

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).

附录:请考虑变量的正确命名约定.i 不是你的变量的好名字.

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

这篇关于在两个类之间共享一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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