如何在C#.NET中声明公共变量(如VB.NET模块中的变量)? [英] How can i declare public variable in C#.NET ( like variable in VB.NET Module ) ?

查看:215
本文介绍了如何在C#.NET中声明公共变量(如VB.NET模块中的变量)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我对C#.NET有点困惑.

使用VB.NET开发应用程序时,可以使用模块.
我在此模块中声明了公共变量,并从项目的所有部分对其进行访问.

但是,当我更改为C#.Net时,C#.NET中没有模块.

我应该如何进行?

如何在C#.NET中声明全局变量?

请帮助...

Hi all,

I am a little confused with C#.NET.

When I develop an app using VB.NET, I can use Module.
I declare public variable in this module and access it from all part of the project.

But, when I change to C#.Net, there is no module in C#.NET.

How should I proceed?

How do I declare Global Variable in C#.NET?

Please Help...

推荐答案

C#没有全局变量的概念:所有内容都是类范围.
但是(就像VB一样),您可以声明static类并像访问全局类一样访问其中的所有内容:
C# has no concept of global variables: everything is class scope.
However (just like VB) you can declare a static class and access everything in it as if they were global:
public static class Globals
   {
   public static int MyGlobalValue = 42;
   }

...


private void MyMethodSomewhereInAClass()
   {
   Console.WriteLine(Globals.MyGlobalValue);
   MyGlobalValue += 23;
   }

从技术上讲,该类不必是静态的,但是由于您无需使其实例化,所以这是个好主意.

Technically, the class does not need to be static, but since you should not need to instatiate it, it is a good idea.


class MyClass {
    public int MemberOne;
    internal int MemberTo = 13; //can initialize
    internal protected string MemberThree;
    private System.DataTime Time; //can omit "private": default for class/struct
    //property, one of several forms of declaration:
    public int MemberFour { get; set; } 
}



在有意列出的所有访问修饰符中:全部学习它们.
根据经验,不应该鼓励使用公共场所,而应该首选属性.

现在,问这样的问题会浪费任何人的时间,使您无所适从.首先,阅读手册并进行练习.阅读我的废话说明:
我的程序有问题.请帮忙! [什么是Apache Struts和JBoss Hibernate [ ^ ]. (忽略该主题,请阅读我的答案.)

这可能会让您大开眼界: http://norvig.com/21-days.html [



In intentionally listed all access modifiers: learn them all.
As a rule of thumb, public fields should be discouraged and properties preferred.

Now, asking questions like that will waste anyone''s time and get you nowhere. First, read a manual and do exercises. Read my non-nonsense instructions:
I have a problem with my program. Please help![^].

Don''t forget this: What are Apache Struts and JBoss Hibernate[^]. (Ignore the topic, read my Answer.)

This might open your eyes: http://norvig.com/21-days.html[^] (how much time do you need?).

Good luck.

—SA


公共静态字符串VariableName;
//写入程序文件
public static String VariableName;
//write in program file


这篇关于如何在C#.NET中声明公共变量(如VB.NET模块中的变量)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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