TryParse static but inherited
How can I simulate inheritance for static methods?
I have a few derived classes 开发者_开发技巧and I would like each of them to have a static "TryParse" method.
There is no way to do inheritance of static methods. Inheritance only exists for instance level members, not class level members. This answer expands on this topic.
static method cannot be virtual.
You cannot.
What, that isn't good enough?
There are a couple different ways to get around this limitation, none of which are good.
First, use the standard interface definition to require a TryParse method on instances. In order to use this, of course, you have to have an instance. An example of this would be the Create method of IActivityTemplateFactory. The method doesn't need to be instance, and in fact most factories you'll find are static (whether or not that's a good thing is another question). But in order to be able to 1) locate a factory for an Activity and 2) call that method which 3) can be overridden by child types it must be defined within an interface.
Second is to use Attributes. An example would be the TypeConverterAttribute. You might be able to leverage this type to do what you want, or you can create something similar that will have your TryParse method.
AFAIK you cannot get inheritance working with static methods. But what you could do is you could declare an instance method (probably having a "protected" access modifier) that will perform an actual parsing and override that method instead:
public abstract class MyBaseClass
{
protected virtual bool TryParseInner(string s) { ... }
}
Now your static method will look like the following:
public static bool TryParse<T>(string s, out T result) where T: MyBaseClass, new()
{
bool ret = false;
result = new T();
ret = result.TryParseInner(s);
if (!ret) result = null;
return ret;
}
The down side of this approach is the generic type constraint declared on TryParse
method which forces sub-classes to have a parameterless constructor.
Hope this will help you.
精彩评论