你有一个带字符串属性的枚举吗?

时间:2013-05-19 11:10:16

标签: c# wcf

我正在尝试开发一个轻型客户端/服务器程序。 “admin”程序应能够在安装了客户端程序的情况下将常用命令发送到多个本地客户端计算机。

我有一个Enum来控制像这样的常用命令:

public enum Command
{
    Reboot,
    StartService,
    ShowMsg
}

有了这个,我可以从管理程序发送命令,如下所示:

Command.Reboot

在客户端程序中,我可以使用switch语句来执行该命令所要求的内容。

但是,对于枚举的某些部分,我需要一个字符串属性来发送它。

与管理员计划一样,我想发送以下内容:

Command.ShowMsg("Hi, this is a string message")

我如何做到这一点?我希望你理解我的问题。

3 个答案:

答案 0 :(得分:1)

你可以有一个包含枚举的类,如下所示:

enum CommandType
{
    Reboot,
    StartService,
    ShowMsg
}
[DataContract]
class Command
{
    [DataMember]
    public CommandType CmdType
    {
        get;
        set;
    }
    [DataMember]
    public string Value
    {
        get;
        set;
    }
    public CommandType(CommandType cmd, string value = null)
    {
        CmdType = cmd;
        Value = value;
    }
}

然后在需要时使用它:

new Command(CommandType.ShowMsg, "Hi, this is a string message.");

答案 1 :(得分:0)

您可以通过更改服务合同来实现。所以在合同中你可以拥有

interface IFooService
{
    void Execute(Command cmd);
    void ExecuteWithParam(Command cmd, string param1);
}

然而,这会给试图了解如何使用此类API的人带来问题。如果您稍后尝试重构该服务,则还存在维护问题。因此,更好的选择是每个枚举值使用一个专用方法,而不是使用通用Execute方法(或任何你称之为的方法)并传递枚举,如下所示:

interface IFooService
{
    void Reboot();
    void StartService(string[] args);
    void ShowMsg(string msg);
}

答案 2 :(得分:0)

我会用课来做这件事。

public class ServiceObject{

public String command {get;set;}
public String message {get;set;}

  public ServiceObject(String command,String message){
   this.command = command;
   if(message!=null)
     this.message = message;

  }

}

您可以通过执行

创建此对象
new ServiceObject("ShowMessage","This is a Service Object");

new ServiceObject("Restart",null);

现在在服务器端只接受服务对象

您可以通过执行ServiceObject.commandServiceObject.message

来检查其属性