简体   繁体   中英

How to declare Types in c#

I am not sure what is the correct name for what I am looking for!

What I am trying to do is to make a method to update a status bar text, and color it as red if it is a error message or green if it is a success message:

public void UpdateStatus(string message, MessageType type)
{
      if(type == MessageType.Error)
      {
           statusText.Text = message;
           statusText.ForeColor = Color.Red;
      }

      if(type == MessageType.Success)
      {
           statusText.Text = message;
           statusText.ForeColor = Color.Green;
      }
}

And here is the MessageType

public class MessageType
{
    class Error
    {
       //What to do here?
    }

    class Success
    {
        //What to do here?
    }
}

So how can I define this MessageType class, and how is it called? Interface? Enum? what??

Thanks.

PS: I know I can just use Color as the second parameter for UpdateStatus method I wrote, but I want to learn how to make it like what I said.

You're trying to make an enum type :

public enum MessageType {
    Success,
    Error
}

I think you just need an enum :

public enum MessageType { Error, Success }

and then your if(type == MessageType.Error) just works.

You are looking for an enum in this case:

public enum MessageStatus
{
  Failure,
  Success
}

You probably want an enum:

public enum MessageType
{
    Error,
    Success
}

Then in code that uses the enum you would do something like:

if (msg == MessageType.Error)
    // show error info
else
    // show success info
public enum MessageType {Error, Success};

I think you want an enum should be something like

public enum MessageType { Error, Success };

Take a look http://msdn.microsoft.com/en-us/library/sbbt4032(v=vs.71).aspx for more info.

If you decide to go with the use of an enum, using:

public enum MessageType
{
    Failure,
    Success
}

... then you can handle it using a switch-case, like so:

public void UpdateStatus(string message, MessageType type)
{
   statusText.Text = message;

   switch (type)
   {
       case MessageType.Error:
           statusText.ForeColor = Color.Red;
           break;

      case MessageType.Success:
           statusText.ForeColor = Color.Green;
           break;
   }
}

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