C#方法返回3个可能的枚举中的1个

时间:2011-10-07 15:48:54

标签: c# methods return-value

我有以下三个枚举:

public enum SensorTypeA{A1,A2,...,A12};
public enum SensorTypeB{B1,B2,...,B12};
public enum SensorTypeC{C1,C2,...,C12};

我正在通过串口与传感器电路进行通信,并想知道在“x”位置使用了哪个传感器,所以我创建了一个方法

public ???? GetSensorTypeAtLocation(int x)
{
   ...
   // Send serial command and receive response.
   string responseCommand = SendReceive(String.Format("SR,ML,{0},\r", x));

   // Process response command string and return result.
   return ???? (could be any of the 3 possible enums)
}

有没有办法可以返回任何可能的枚举?转为object?更好的方式?

谢谢!

修改

每种传感器类型都有多个传感器。我更改了枚举以反映这一点。

2 个答案:

答案 0 :(得分:2)

这看起来像是Enum.TryParse()的作业。

public Enum GetSensorTypeAtLocation(int x)
{
   ...
   // Send serial command and receive response.
   string responseCommand = SendReceive(String.Format("SR,ML,{0},\r", x));

   //Try to parse the response into a value from one of the enums;
   //the first one that succeeds is our sensor type.
   SensorTypeA typeAresult;
   if(Enum.TryParse(responseCommand, typeAResult)) return typeAresult;
   SensorTypeB typeBresult;
   if(Enum.TryParse(responseCommand, typeBResult)) return typeBresult;
   SensorTypeC typeCresult;
   if(Enum.TryParse(responseCommand, typeCResult)) return typeCresult;
}

问题是你不能根据返回类型创建重载,因此你不会确切地知道系统将返回什么(但CLR会在运行时知道,你可以查询返回值的类型来获取具体答案)。

我会认真考虑包含A,B和C值的枚举SensorType。然后,该函数可以根据传感器给出的响应类型返回一个明确的答案:

public SensorType GetSensorTypeAtLocation(int x)
{
   ...
   // Send serial command and receive response.
   string responseCommand = SendReceive(String.Format("SR,ML,{0},\r", x));

   // Process response command string and return result.
   SensorTypeA typeAresult;
   if(Enum.TryParse(responseCommand, typeAResult)) return SensorType.A;
   SensorTypeB typeBresult;
   if(Enum.TryParse(responseCommand, typeBResult)) return SensorType.B;
   SensorTypeC typeCresult;
   if(Enum.TryParse(responseCommand, typeCResult)) return SensorType.C;
}

现在,您可以从返回值本身知道传感器的类型。

答案 1 :(得分:0)

您可以完全忽略问题的Enum部分,因为问题的根源是“函数可以返回多个类型”。答案是肯定的,但你必须返回更高级别的课程,在这种情况下Object,你需要在返回后进行类型检查:

    public enum SensorTypeA { A = 0 };
    public enum SensorTypeB { B = 1 };
    public enum SensorTypeC { C = 2 };

    private object GetSensorTypeAtLocation()
    {
        return SensorTypeB.B;
    }

    private void YourMethod(object sender, EventArgs e)
    {
        object value = GetSensorTypeAtLocation();
        if (value is SensorTypeA)
        {
            Console.WriteLine("A");
        }
        else if (value is SensorTypeB)
        {
            Console.WriteLine("B");
        }
        else if (value is SensorTypeC)
        {
            Console.WriteLine("C");
        }
        else
        {
            Console.WriteLine("Unknown");
        }
    }