如何将枚举值与consructor对象进行比较 [英] How to compare enum values with consructor objects
本文介绍了如何将枚举值与consructor对象进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的枚举值是这样的
Hi,
I have enumerator values like this
public enum Buses
{
CANBusRed = 1,
CANBusYellow = 2 ,
CANBusGreen = 3 ,
CANBusOrange = 4
};
我有像这样的3个对象的构造函数
I have constructor with 3 objects in it like this
public class MsgIdTimeStampMap
{
string msgId;
double timeStamp;
public Buses Bus { get; set; }
public string MsgId
{
get
{
if (!String.IsNullOrEmpty(msgId))
return msgId.ToUpper();
else
return string.Empty;
}
set { msgId = value; }
}
public double TimeStamp
{
get
{
//Double.IsNullOrEmpty(timeStamp)
return timeStamp;
//else
// return string.Empty;
}
set { timeStamp = value; }
}
public MsgIdTimeStampMap(Buses bus, string msgId, double timeStamp)
{
this.Bus = bus;
this.msgId = msgId;
this.timeStamp = timeStamp;
}
}
现在我需要将枚举值与构造函数的对象进行比较。但无法做到这一点
我正在尝试这样的事情
Now I need to compare enum values with object of constructor. But unable to do that
I am trying something like this
for (int m = 0; m < CANMsgIdList.Count; m++)
{
if (CANMsgIdList[m].Bus == ConsoleApplication13.Buses.CANBusRed)
{
reds.Add(index);
}
index++;
}
List<double> times = new List<double>();
foreach (var i in reds)
if ((i < (index - 1)) && CANMsgIdList[i + 1].Bus == ConsoleApplication13.Buses.CANBusYellow)
{
arrList3.Add(CANMsgIdList[i + 1].TimeStamp - CANMsgIdList[i].TimeStamp);
}
double av = times.Sum() / times.Count;
任何人都可以帮我解决这个问题????
谢谢
John
Can anyone help me in solving this????
Thanks
John
推荐答案
转换和比较枚举和字符串:
1.如果可能的话,你想要避免这种情况:理想情况下,你到处都在使用Enum,而且永远不必转换它。但是,如果你必须这样做:
2. if(someString.Equals(Buses.CANBusYellow.ToString()){// do stuff}
这是最糟糕的方式:需要转换。
3.使用.NET 2.0你有Enum .Parse [ ^ ];在.NET 4.0中,您可以使用Enum.TryParse [ ^ ]。
我强烈建议你使用Enum.TryParse:
Converting and Comparing Enum and string:
1. if at all possible, you want to avoid this: ideally you'd be using the Enum everywhere, and never have to convert it. But, if you have to do it:
2. if(someString.Equals(Buses.CANBusYellow.ToString()) { // do stuff }
This is the worst way to do it: requires conversion.
3. with .NET 2.0 you have Enum.Parse [^]; in .NET 4.0 you can use Enum.TryParse [^].
I strongly suggest you use Enum.TryParse:
Buses theBus;
if (Enum.TryParse(someString, out theBus))
{
switch (theBus)
{
case Buses.CANBusYellow:
// do yellow stuff
break;
case Buses.CANBusGreen:
// do green stuff
break;
// and so on
}
}
else
{
MessageBox.Show(someString + " is not a bus.");
}
注意:此代码是从内存中写入的,未经过测试。
Note: this code is written from memory, and is not tested.
这篇关于如何将枚举值与consructor对象进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文