简体   繁体   English

C / C ++全局变量的等效项是什么?

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

I am new to C#. 我是C#的新手。 Come from the C/C++ environment. 来自C / C ++环境。 My application has a List<Model> which is required all over the place, by different classes. 我的应用程序有一个List<Model> ,它是各地不同类所需要的。 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. 我尝试更改一些参数,并将该特定变量作为ref传递,但是一旦给它分配了等号,我就会得到一个副本。 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. 甚至使其具有getter / setter属性。

Create a Public Class and have the content you wish to pass declared static within the class. 创建一个公共类,并在类中将您希望传递的内容声明为static。 Then just access it as NameOfClass.NameOfMethod() 然后以NameOfClass.NameOfMethod()的身份访问它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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