为什么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) 有没有一种简单的方法来实现它,如果可能的话,不需要实例化对象:
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) 在我的代码中有一个接口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)