Like enum but for objects
I have a custom class "Error" and some pre-created errors (let's call them A, B and C). Now I'd love to group these pre-create开发者_如何转开发d ones under one group (for example, "StockErrors") and use them kind of like an enum:
private void SomeFunction(Error NewError)
{
if (NewError == StockErrors.A) DoSomething(); // this is what I need.
}
Any ideas how I could accomplish this? It's probably something extremely simple...
Thanks in advance!
Make a static
class called StockErrors
with public static readonly
fields of type Error
that are initialized to the appropriate values. (You can also use properties)
Depending on your Error
class, you may also need to override ==
, !=
, Equals
, and GetHashCode
to use value semantics.
Something like this:
public static class StockErrors
{
public static readonly Error A = new Error("A");
public static readonly Error B = new Error("B");
public static readonly Error C = new Error("B");
}
That's the dead simplest declaration, though it exposes fields, which is generally considered bad form. To make it a little more acceptable, you could declare the fields as private
, then expose them in public static
properties.
Also, if your Error
class can't be constructed solely based on constant values, then you would need to initialize the variables in the static constructor. Here's an example where the values are exposed by properties and initialized in the static constructor:
public static class StockErrors
{
private static readonly Error a;
private static readonly Error b;
private static readonly Error c;
public static Error A { get { return a; } }
public static Error B { get { return b; } }
public static Error C { get { return c; } }
static StockErrors()
{
a = new Error(...);
b = new Error(...);
c = new Error(...);
}
}
精彩评论