简体   繁体   中英

How can I force inheriting classes to implement a static method in C#?

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.

abstract classes with static methods don't seem to work:

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

and interfaces don't seem to work either:

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

Is there some workaround for this to have the compiler check if inheriting classes implement a static method with a certain signature or not?

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

Hope this helps!!

This cannout be done.

Have a look at Why can't I have abstract static methods in c#?

It doesn't make sense to force clients to implement a static method - static methods are "immutable." (There's probably a better way to describe them but that's all my mind can come up with right now!)

If some sort of overriding is required, I would consider re-visiting the design, possibly using some form of a combination of singletons and injection.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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