Zastanawiam się nad wyliczeniami C# i co dzieje się z duplikatami wartości. I stworzył następującą mały program do testowania rzeczy:C# Wyliczenia i powielone wartości - niebezpieczeństwa?
namespace ConsoleTest
{
enum TestEnum
{
FirstElement = -1,
SecondElement,
ThirdElement,
Duplicate = FirstElement
}
/// <summary>
/// Summary description for MainConsole.
/// </summary>
public class MainConsole
{
/// <summary>
/// Constructor for the class.
/// </summary>
public MainConsole()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Entry point for the application.
/// </summary>
/// <param name="args">Arguments to the application</param>
public static void Main(string[] args)
{
TestEnum first = TestEnum.FirstElement;
TestEnum second = TestEnum.SecondElement;
TestEnum duplicate = TestEnum.Duplicate;
foreach (string str in Enum.GetNames(typeof(TestEnum)))
{
Console.WriteLine("Name is: " + str);
}
Console.WriteLine("first string is: " + first.ToString());
Console.WriteLine("value is: " + ((int)first).ToString());
Console.WriteLine("second string is: " + second.ToString());
Console.WriteLine("value is: " + ((int)second).ToString());
Console.WriteLine("duplicate string is: " + duplicate.ToString());
Console.WriteLine("value is: " + ((int)duplicate).ToString());
TestEnum fromStr = (TestEnum)Enum.Parse(typeof(TestEnum), "duplicate", true);
Console.WriteLine("fromstr string is: " + fromStr.ToString());
Console.WriteLine("value is: " + ((int)fromStr).ToString());
if (fromStr == TestEnum.Duplicate)
{
Console.WriteLine("Duplicate compares the same as FirstElement");
}
else
{
Console.WriteLine("Duplicate does NOT compare the same as FirstElement");
}
}
}
}
która produkuje następujące dane wyjściowe:
Name is: SecondElement
Name is: ThirdElement
Name is: FirstElement
Name is: Duplicate
first string is: FirstElement
value is: -1
second string is: SecondElement
value is: 0
duplicate string is: FirstElement
value is: -1
fromstr string is: FirstElement
value is: -1
Duplicate compares the same as FirstElement
Press any key to continue . . .
to wydaje się być dokładnie tym, czego chcą i oczekują, ponieważ jestem konstruowaniem czegoś, że wersja Tag będzie się zwiększał co jakiś czas, więc chcę coś, co mogę "przydzielić" do aktualnej wersji, a nawet porównać z nią.
Oto jednak pytanie: jakie są pułapki tego podejścia? Czy jest jeden? Czy to po prostu zły styl (nie chcę skończyć na thedailywtf)? Czy jest o wiele lepszy sposób robienia czegoś takiego? Jestem na .NET 2.0 i NIE mam opcji, aby przejść do 3.5 lub 4.0.
Opinie są mile widziane.
Widzę przeliczanie konwertowane na ciągi znaków, widzę sznur przetwarzany na emum. Co robisz, robisz poprawnie, ale jaki jest twój cel? –
@Rob Elliott - niektóre z tych rzeczy będą wprowadzane i odczytywane z baz danych opartych na łańcuchach znaków (nie mój wybór), więc muszę się upewnić, że otrzymam to, czego oczekuję. –