如何强制继承类在 C# 中实现静态方法? [英] How can I force inheriting classes to implement a static method in C#?

查看:30
本文介绍了如何强制继承类在 C# 中实现静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的就是确保Item类的子类实现一个静态方法,我希望它被检查在编译时避免运行时错误.

All I want to do is make sure that child classes of the class Item implement a static method and I want this to be checked at compile time to avoid runtime errors.

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

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

ERROR: A static member cannot be marked as override, virtual, or abstract

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()

ERROR: Customer does not implement interface member 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();
}

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

推荐答案

我为您的方案找到了一个解决方法:

There is a workaround i figured out for your scenario:

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();
    }
}

希望这有帮助!!

这篇关于如何强制继承类在 C# 中实现静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆