为什么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;
}
....
}
假设您问为什么不能这样做:
public interface IFoo {
void Bar();
}
public class Foo: IFoo {
public static void Bar() {}
}
从语义上讲,这对我来说没有意义。接口上指定的方法应该用于指定与对象交互的契约。静态方法不允许您与对象交互 - 如果您发现自己的实现可以静态化,您可能需要问自己该方法是否真的属于接口。
To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.
public class Animal: IListItem {
/* Can be tough to come up with a different, yet meaningful name!
* A different casing convention, like Java has, would help here.
*/
public const string AnimalScreenName = "Animal";
public string ScreenName(){ return AnimalScreenName; }
}
对于更复杂的情况,您始终可以声明另一个静态方法并委托给它。在尝试举一个例子时,我想不出任何理由你会在静态和实例上下文中做一些不平凡的事情,所以我会给你一个 FooBar blob,并将其视为它可能的指示这不是一个好主意。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)