开发者

C# equivalent of the Ruby symbol

I'm developing a little C# application for the fun. I l开发者_运维百科ove this language but something disturb me ...

Is there any way to do a #define (C mode) or a symbol (ruby mode).

The ruby symbol is quite useful. It's just some name preceded by a ":" (example ":guy") every symbol is unique and can be use any where in the code.

In my case I'd like to send a flag (connect or disconnect) to a function.

What is the most elegant C# way to do that ?

Here is what i'd like to do :

BgWorker.RunWorkersAsync(:connect)
//...

private void BgWorker_DoWork(object sender, DoWorkEventArgs e)
{
  if (e.Arguement == :connect)
    //Do the job
}

At this point the my favorite answer is the enum solution ;)


In your case, sending a flag can be done by using an enum...

public enum Message
{
  Connect,
  Disconnect
}

public void Action(Message msg)
{
   switch(msg)
   {
      case Message.Connect: 
         //do connect here
       break;
      case Message.Disconnect: 
          //disconnect
       break;
      default:
          //Fail!
       break;
   }
}


You could use a string constant:

public const string Guy = "guy";

In fact strings in .NET are special. If you declare two string variable with the same value they actually point to the same object:

string a = "guy";
string b = "guy";
Console.WriteLine(object.ReferenceEquals(a, b)); // prints True


C# doesn't support C-style macros, although it does still have #define. For their reasoning on this take a look at the csharp FAQ blog on msdn.

If your flag is for conditional compilation purposes, then you can still do this:

#define MY_FLAG

#if MY_FLAG
  //do something
#endif

But if not, then what you're describing is a configuration option and should perhaps be stored in a class variable or config file instead of a macro.


Similar to @Darin but I often create a Defs class in my project to put all such constants so there is an easy way to access them from anywhere.

class Program
{
    static void Main(string[] args)
    {

        string s = Defs.pi;
    }
}
class Defs
{

    public const int Val = 5;
    public const string pi = "3.1459";
} 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜