相关疑难解决方法(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#界面中使用静态方法吗?

我想实现一个集合,其项目需要进行空虚测试.在引用类型的情况下,将测试为null.对于值类型,必须实现空测试,并且可能选择表示空白的特定值.

我的T的一般集合应该是两个值和参考类型值可用(意味着Coll<MyCalss>Coll<int>都应该是可能的).但我必须以不同方式测试引用和值类型.

拥有一个实现IsEmpty()方法的接口,从我的泛型类型中排除这个逻辑,这不是很好吗?但是,当然,这个IsEmpty()方法不能是成员函数:它无法在空对象上调用.

我找到的一个解决方法是将收集项目存储为对象,而不是Ts,但它让我头疼(围绕拳击和强类型).在旧的C++中没有问题:-)

下面的代码演示了我想要实现的目标:

using System;
using System.Collections.Generic;

namespace StaticMethodInInterfaceDemo
{
  public interface IEmpty<T>
  {
    static T GetEmpty();  // or static T Empty;

    static bool IsEmpty(T ItemToTest);
  }


  public class Coll<T> where T : IEmpty<T>
  {
    protected T[] Items;

    protected int Count;


    public Coll(int Capacity)
    {
      this.Items = new T[Capacity];
      this.Count = 0;
    }

    public void Remove(T ItemToRemove)
    {
      int Index = Find(ItemToRemove);

      // Problem spot 1: This throws a compiler error: "Cannot convert null …
Run Code Online (Sandbox Code Playgroud)

c# methods static interface

0
推荐指数
1
解决办法
770
查看次数

标签 统计

c# ×2

interface ×1

language-features ×1

methods ×1

oop ×1

static ×1