相关疑难解决方法(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#接口静态方法调用泛型

有没有一种简单的方法来实现它,如果可能的话,不需要实例化对象:

interface I
{
     static  string GetClassName();
}

public class Helper
{

    static void PrintClassName<T>() where T : I
    {
         Console.WriteLine(T.GetClassName());
    }
}
Run Code Online (Sandbox Code Playgroud)

c# generics inheritance static interface

28
推荐指数
2
解决办法
3万
查看次数

每个实现都有唯一的静态接口属性吗?

在我的代码中有一个接口damagable

public interface Damagable
{
    public static float maxHealth { get; set; }
    public float currentHealth { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

不同的类实现damagable,其中currentHelath每个实例都是唯一的。这个想法是,给定类型的不同实例都将共享相同的内容maxHealth,以处理诸如基于 的再生和损坏之类的事情maxHealth

这里的关键字能static解决问题吗?

我可以maxHealth在每个类的构造函数中进行设置,但我希望有一种方法可以使其每个类都是静态的。

有没有办法让接口属性在实现它的每个类上都不同,而该类的每个实例都具有相同的值,或者是否有更好的方法来做到这一点?

最终我将有多个类,例如:

public class LargeObstacle : Damagable
{
    public float maxHealth { get; set; } = 100;
    public float currentHealth { get; set; }
}
public class SmallObstacle : Damagable
{
    public float maxHealth { get; set; } = 40;
    public …
Run Code Online (Sandbox Code Playgroud)

c#

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

标签 统计

c# ×3

generics ×1

inheritance ×1

interface ×1

language-features ×1

oop ×1

static ×1