Static virtual in C#
Argh, this is annoying. I need a Handler type with a virtual string GetProduct() method so that derived types "know" what product they are for. However, I don't want to have to create an instance of the actual class every time I need to ask for its product... I want it to be a virtual method. Too bad - C# doesn't allow virtual static methods.
What I ended up with was this: each class derived from Handler has a read-only static string property Product, each of them returning the product that class can handle. In the method where I need that product (when populating a drop-down for example) I use reflection to get the value of the property:
I'm not really happy with this - I miss Delphi's "class" type which allowed a much more elegant solution. I'll edit this if I find something I like better.
Edit: Heh, I found a solution I like better: attributes. I define the following class:
Now I can decorate the handlers with a
First time I create a custom attribute. Helpful and elegant, so it won't be the last.
What I ended up with was this: each class derived from Handler has a read-only static string property Product, each of them returning the product that class can handle. In the method where I need that product (when populating a drop-down for example) I use reflection to get the value of the property:
- if (handlerType.BaseType != typeof (Handler))
- return;
- var product = (string) handlerType.GetProperty("Product").GetValue(null, null);
I'm not really happy with this - I miss Delphi's "class" type which allowed a much more elegant solution. I'll edit this if I find something I like better.
Edit: Heh, I found a solution I like better: attributes. I define the following class:
- [AttributeUsage(AttributeTargets.Class)]
- internal class ProductInfo: Attribute
- {
- public string Product { get; private set; }
- public ProductInfo(string product)
- {
- Product = product;
- }
- }
Now I can decorate the handlers with a
[ProductInfo("xxx")]attribute and extract the product name with
- var attributes = handlerType.GetCustomAttributes(typeof (ProductInfo), true);
- if (attributes.Length == 0)
- return;
- var product = ((ProductInfo) attributes[0]).Product;
First time I create a custom attribute. Helpful and elegant, so it won't be the last.
Comments