简体   繁体   中英

What is the equivalent of a C/C++ global variable?

I am new to C#. Come from the C/C++ environment. My application has a List<Model> which is required all over the place, by different classes. The problem is that a copy will not do because this statement:

dataGrid.ItemsSource = myModelList;

requires the original by address. I tried changing some arguments around and passing that particular variable as ref but as soon as it is assigned with an equal sign, I end up with a copy. Correct?

You could make it a singleton. However a concrete List needed all over the place would make me have a serious think about my design.

At the very least you should consider writing a class to control access to the list (add, remove, clear etc), and making that "global", otherwise you are going to be in deep in the brown stuff, until it hits the fan.

You can create a public class for it with a public static List inside it. That one you then can access everywhere.

eg

public class FakeGlobal
{
    public static List<Model> MyModelList = new List<Model>();
}

or even make it a property with getter/setter.

Create a Public Class and have the content you wish to pass declared static within the class. Then just access it as NameOfClass.NameOfMethod()

public class NameOfClass
{
    public static RETURNTYPE NameOfMethod()
    {
        // Your Code
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM