我如何可以强制继承类来实现在C#中的静态方法? [英] How can I force inheriting classes to implement a static method in C#?
问题描述
所有我想要做的就是确保类的子类的项目实施静态方式,我想这是检查。在编译时避免运行时错误
抽象类的静态方法似乎不工作:
错误:静态成员
不能被标记为
超控,虚拟或抽象
块引用>
公共抽象类项目
{
公共静态抽象项目GetHistoricalItem(INT编号,日期pastDateTime);
}
公共类客户:项目
{
公共静态覆盖客户GetHistoricalItem(INT编号,日期pastDateTime)
{
返回新顾客();
}
}
公共类地址:项目
{
公共静态覆盖地址GetHistoricalItem(INT编号,日期pastDateTime)
{
返回新地址();
}
}
和接口似乎不工作或者:
错误:客户不实现接口
会员GetHistoricalItem()
块引用>
公共类客户:项目,HistoricalItem
{
公共静态客户GetHistoricalItem(INT编号,日期pastDateTime)
{
返回新客户();
}
}
公共类地址:项目,HistoricalItem
{
公共静态地址GetHistoricalItem(INT编号,日期pastDateTime)
{
返回新地址();
}
}
接口HistoricalItem
{
项目GetHistoricalItem();
}
有一些解决方法这让编译器检查是否继承类实现一个静态方法具有一定的签名或不?
解决方案有一种变通方法我想通了你场景:
公共类客户:参考<客户>中IHistoricalItem
{
}
公共类地址:参考<地址> ;, IHistoricalItem
{
}
公共接口IHistoricalItem
{
}
酒店的公共类参考< T>其中T:IHistoricalItem,新的()
{
公共静态牛逼GetHistoricItem(INT编号,日期pastDateTime)
{
返回新T();
}
}
希望这有助于!
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!!
这篇关于我如何可以强制继承类来实现在C#中的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!