简体   繁体   English

TryParse静态但继承

[英]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. 我有一些派生类,我希望每个类都有一个静态的“ TryParse”方法。

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. 这个答案扩展了这个主题。

静态方法不能是虚拟的。

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. 首先,使用标准接口定义在实例上需要TryParse方法。 In order to use this, of course, you have to have an instance. 为了使用此功能,当然,您必须有一个实例。 An example of this would be the Create method of IActivityTemplateFactory . 一个示例就是IActivityTemplateFactory的Create方法。 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. 但是,为了能够1)找到一个Activity的工厂,并2)调用该方法(3)可以被子类型覆盖,必须在接口中定义该方法。

Second is to use Attributes. 其次是使用属性。 An example would be the TypeConverterAttribute . 一个例子就是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. 您可能可以利用这种类型来执行所需的操作,或者可以创建类似的具有TryParse方法的内容。

AFAIK you cannot get inheritance working with static methods. AFAIK,您无法使用静态方法获得继承。 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. 这种方法的TryParse是在TryParse方法上声明的通用类型约束,该约束迫使子类具有无参数构造函数。

Hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM