开发者

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

开发者 https://www.devze.com 2022-12-13 21:21 出处:网络
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.

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 GetHist开发者_C百科oricalItem(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.


Seems it's not possible, take a look: Is there a way to force a C# class to implement certain static functions?


By definition a static method cannot be implemented in derived classes.

0

精彩评论

暂无评论...
验证码 换一张
取 消