【问题标题】:How can I force inheriting classes to implement a static method in C#?如何强制继承类在 C# 中实现静态方法?
【发布时间】:2010-12-26 17:41:18
【问题描述】:

我想要做的就是确保Item 的子类实现一个 static 方法,并且我希望对此进行检查在编译时避免运行时错误。

带有静态方法的抽象类似乎不起作用:

错误:静态成员 不能标记为 覆盖、虚拟或抽象

public abstract class Item
{
    public static abstract Item GetHistoricalItem(int id, DateTime pastDateTime);
}

public class Customer : Item
{
    public static override Customer GetHistoricalItem(int id, DateTime pastDateTime)
    {
        return new Customer();
    }
}

public class Address : Item
{
    public static override Address GetHistoricalItem(int id, DateTime pastDateTime)
    {
        return new Address();
    }
}

界面似乎也不起作用:

错误:客户未实现接口 成员GetHistoricalItem()

public class Customer : Item, HistoricalItem
{
    public static Customer GetHistoricalItem(int id, DateTime pastDateTime)
    {
        return new Customer();
    }
}

public class Address : Item, HistoricalItem
{
    public static Address GetHistoricalItem(int id, DateTime pastDateTime)
    {
        return new Address();
    }
}

interface HistoricalItem
{
    Item GetHistoricalItem();
}

是否有一些解决方法可以让编译器检查继承的类是否实现了具有特定签名的静态方法?

【问题讨论】:

    标签: c# interface static methods abstract


    【解决方案1】:

    我为您的方案想出了一个解决方法:

    public class Customer : Reference<Customer>, IHistoricalItem
    {
    }
    
    public class Address : Reference<Address>, IHistoricalItem
    {
    }
    
    public interface IHistoricalItem
    {
    }
    
    public class Reference<T> where T : IHistoricalItem, new()
    {
        public static T GetHistoricItem(int id, DateTime pastDateTime)
        {
            return new T();
        }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 即使 Customer/Address 没有实现 GetHistoricItem 函数,它也不会产生任何错误。我错过了什么吗?
    • @Yongke Bill Yu:为什么你认为应该?
    【解决方案2】:

    【讨论】:

      【解决方案3】:

      强制客户端实现静态方法是没有意义的——静态方法是“不可变的”。 (可能有更好的方式来描述它们,但我现在只能想到这些了!)

      如果需要某种覆盖,我会考虑重新设计,可能使用单例和注入的某种形式的组合。

      【讨论】:

      • 我有一个类 Item ,各种对象继承,例如客户、地址等。如果一个类是 Item 类型,那么我希望能够在其上调用一个名为 GetHistoricalItem() 的工厂方法。所以我希望能够说 Address address = Address.GetHistoricalItem(...)。而且我想在编译时知道我所有继承 Item 的类都这样做。它的工作方式应该与实例方法相同。
      • @EdwardTanguay 这是很久以前的事了,但您最好创建某种 History 类(实例),其中包含从中检索地址的常规方法。例如,注册将是一个好名字。
      【解决方案4】:
      【解决方案5】:

      根据定义,静态方法不能在派生类中实现。

      【讨论】:

        猜你喜欢
        • 2016-07-06
        • 2014-10-28
        • 1970-01-01
        • 2011-03-25
        • 1970-01-01
        • 2015-03-20
        • 2013-08-02
        • 1970-01-01
        • 2012-11-14
        相关资源
        最近更新 更多