相关疑难解决方法(0)

为什么C#不允许静态方法实现接口?

为什么C#这样设计?

据我所知,接口只描述行为,并且用于描述实现某些行为的接口的类的合同义务.

如果类希望在共享方法中实现该行为,为什么不应该这样做呢?

这是我想到的一个例子:

// These items will be displayed in a list on the screen.
public interface IListItem {
  string ScreenName();
  ...
}

public class Animal: IListItem {
    // All animals will be called "Animal".
    public static string ScreenName() {
        return "Animal";
    }
....
}

public class Person: IListItem {

    private string name;

    // All persons will be called by their individual names.
    public string ScreenName() {
        return name;
    }

    ....

 }
Run Code Online (Sandbox Code Playgroud)

c# oop language-features

435
推荐指数
9
解决办法
18万
查看次数

如何强制继承类在C#中实现静态方法?

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

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

错误:无法将静态成员标记为覆盖,虚拟或抽象

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

和接口似乎也不起作用:

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

public class Customer : Item, HistoricalItem
{
    public static Customer GetHistoricalItem(int id, DateTime pastDateTime)
    { …
Run Code Online (Sandbox Code Playgroud)

c# methods static interface abstract

20
推荐指数
3
解决办法
1万
查看次数

标签 统计

c# ×2

abstract ×1

interface ×1

language-features ×1

methods ×1

oop ×1

static ×1