C#类声明以使用多个数据类型

C#类声明以使用多个数据类型,c#,C#,我在下面声明了public类,以便在例程中返回多种数据类型: public class dataformat { public int nFlag; public String strCommand; public String strData; } 下面是我想要将整数nFlag返回到b时使用的编码: public dataformat TxRxProtocol() { int a; dataformat df = new

我在下面声明了public类,以便在例程中返回多种数据类型:

public class dataformat
{
    public int nFlag;
    public String strCommand;
    public String strData;
}
下面是我想要将整数nFlag返回到b时使用的编码:

    public dataformat TxRxProtocol()
    {
        int a;
        dataformat df = new dataformat();

        // coding
        // coding
        // coding
        if (a==0) df.nFlag = 1;
        if (a==1) df.nFlag = 2;

        return df;
     }
我试过:

  dataformat b = TxRxProtocol();
  if (b==0) // a condition
  else if (b==1) // a condition
但声明b不是整数时出错

我们如何编写TxRxProtocol()例程,使其能够返回多种类型的值(包括字符串类型),而不仅仅是nFlag整数类型?我们是否必须在其中添加df.strCommand=“Something”或df.strData=“Something”?

尝试以下方法:

 int b = 0;
 dataformat ret = TxRxProtocol();
 b = ret.nFlag;
编译器是对的。它告诉您,您正试图将一个数据格式(返回的数据)分配给变量b(以int表示)

您还可以将b设置为数据格式类型,从而将上述内容简化为:

dataformat b = TxRxProtocol();

当然,“b”的使用取决于你在做什么。

它们的类型不兼容,当然不起作用。。。 你是说:

 dataformat b = TxRxProtocol();

注:类型名称应大写。

变量
b
必须是
数据格式的类型,因此下面是一个示例:

 dataformat b = TxRxProtocol();

它应该是b=TxRxProtocol().nFalg

可以使用隐式转换运算符:

class TxRxProtocol 
{
  public static implicit operator int(TxRxProtocol t)
  {
    return t.nFlag;
  }
}
而不是这个

dataformat b = TxRxProtocol();
if (b==0) // a condition
else if (b==1) // a condition
试试下面的方法

dataformat b = TxRxProtocol();
if (b.nflag==0) // a condition
else if (b.nflag==1) // a condition

您将
b
声明为
int
,但
TxRxProtocol
返回
dataformat
。如果它们兼容,则将其转换为:
b=(int)TxRxProtocol()
heh,您正在尝试将dataformat实例分配给应该指向int的引用。
b
int
,您正在尝试将
TxRxProtocol
类的实例分配给它。我假设您是在Visual studio中编译的。我确信它突出显示了有问题的行。那么,返回整数值的正确方法是什么?老实说,我不会使用这种转换解决方案。你只会让其他阅读你的代码的人感到困惑。实际上,TxRxProtocol()的返回值是任意类型的。我们怎么写呢?实际上,TxRxProtocol()的返回值我希望它是任何类型的。我们怎么写呢?实际上,TxRxProtocol()的返回值我希望它是任何类型的。我们怎么写这个?