如何在C#中将全局变量传递给类

时间:2018-12-23 16:24:16

标签: c#

我正在努力寻找将全局变量传递给类的解决方案。

我试图创建一个公共函数来获取全局变量的值,好像我无法从类中调用该函数。

下面是我的代码:

    string latitude = null;
    string longitude = null;
    public string geturl() {
        return  latitude + "," + longitude;
    }

    public Form1() {
        Watcher = new GeoCoordinateWatcher();

        Watcher.StatusChanged += Watcher_StatusChanged;
        InitializeComponent();
        Watcher.Start();
        ChromiumWebBrowser a = new ChromiumWebBrowser();
        panel1.Controls.Add(a);
        a.Dock = System.Windows.Forms.DockStyle.Fill;
        a.Load("https://drive.google.com/open?id=12j590lCugajX1T64DHKcSiX9RwwBkAeF&usp=sharing");
        CefSettings settings = new CefSettings();
        BrowserLifeSpanHandler blsh = new BrowserLifeSpanHandler();
        a.LifeSpanHandler = blsh;      
    }

    public GeoCoordinateWatcher Watcher = null;

    private void Watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) {
        if (e.Status == GeoPositionStatus.Ready){
            // Display the latitude and longitude.
            if (Watcher.Position.Location.IsUnknown){
                latitude = "Cannot find location data";
            } else {
                latitude = Watcher.Position.Location.Latitude.ToString();
                longitude = Watcher.Position.Location.Longitude.ToString();
            }
        }
    }

    public class BrowserLifeSpanHandler : ILifeSpanHandler {
        public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName,
            WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo,
            IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) {               
            newBrowser = null;
            MessageBox.Show(targetUrl);
            ChromiumWebBrowser b = new ChromiumWebBrowser(targetUrl);
            return false;
        }

        public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser) {
            //
        }

        public bool DoClose(IWebBrowser browserControl, IBrowser browser) {
            return false;
        }

        public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser) {
            //nothing
        }
    }

如何将string geturl()函数的值传递给BrowserLifeSpanHandler类?

1 个答案:

答案 0 :(得分:1)

C#不支持“全局变量”的概念,例如您可能从javascript中知道的那样。

如果您确实需要这样的东西(您应该首先重新考虑设计),则可以定义static class

public static class MyGlobals {
    public static int p1 {get;set;}
    public static string p2 {get;set;}

    public static string getValue() {
        return "somevalue";
    }


}

然后,您可以从代码中的任何位置访问属性值和方法

int v = MyGlobals.p1;
string s = MyGlobals.getValue();