开发者

Checking variable from a different class in C#

Greetings-

I have 开发者_运维百科2 classes. One is called "Programs" and the other is called "Logs". The class called Programs has public const string m_sEnviron = ""; near the top and I need to check what the m_sEnviron variable is set to through my class called Logs. The variable m_sEnviron will get set from a scheduler called Tidal so how can I check its value from a different class. If this is not the best to do this then please let me know what the better ways are.

Thanks in advance.

Regards,

Namespace NightScripts
{
   class Program
   {

      public static string m_sEnviron {get; set;} 

      static void Main(string[] args)
      {

      }

      //Lots of other functions...

   }

   class Logs
   {
      //I try to get access to m_sEnviron but it will not show after I type Program.
   }
}


Well, m_sEnviron isn't a variable (/field) - it is a const; it is always "".

If it was a static property (or field), then Programs.m_sEnviron. If it was an instance property (or field) then someInstance.m_sEnviron should work, since it is public - but I would rename it.

I expect you mean it to be a static field; which can work, but you should at least be a little cautious that this doesn't necessarily play nicely if you start using multiple threads, etc. And public fields are generally best avoided (prefer private fields and public properties).

For example:

public static string Environ {get;set;}

would be a public, static property easily accessible as Program.Environ.


const basically makes the variable static and readonly. So public const string m_sEnviron = ""; means that m_sEnviron will ALWAYS be the empty string. If you try and change it, you will get an error.

However, to access it from a method in the Logs class, you just access it just like a static variable:

string foo = Programs.m_sEnviron;


If I understand your question correctly, you could specify the class where the variable is located as a static class which would therefore not require instantiation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜