那么,我相信它应该允许在泛型类型参数的情况下。它可能简化合同单身班。下面是一个例子:
public interface IEntity {
// some constrains...
DataRow ObjToRow(object obj);
object RowToObj(DataRow dr);
}
//T would be any class inherites from IEntity with default contructor signature.
public interface IMyContract {
T read<T>() where T : IEntity;
void write<T>(T object) where T : IEntity;
}
//everything in the class is static
public static class SqlProvider : IMyContract {
public static T read<T>() where T: IEntity {
DataRow dr = [reading from database]
return T.RowToObj(dr);
}
//compile error here....
public static void write<T>(T obj) where T : IEntity {
DataRow dr = T.ObjToRow(obj);
[ ... commit data row dr to database ... ]
}
}
public static class MyAppleEntity : IEntity {
[... implement IEntity contract normally ... ]
}
public static class MyOrangeEntity : IEntity {
[... implement IEntity contract normally ... ]
}
public class MyTest {
void reading() {
MyAppleEntity apple = SqlProvider.Read<MyAppleEntity>();
MyOrangeEntity orange = SqlProvider.Read<MyOrangeEntity>();
SqlProvider.write<MyAppleEntity>(apple);
SqlProvider.write<MyOrangeEntity>(orange);
}
}
唯一一次一种类型的参考隐含在SqlProvider.read()和写(),T是在调用的点以及身份。没有接口的静态实现,我不得不像这样写。
public class MyAppleEntity : IEntity {
[... implement IEntity contract normally ... ]
}
.....
public T read<T>() where T: IEntity, new() {
DataRow dr = [reading from database]
return new T().RowToObj(dr);
}
几乎没有什么不同,但没有那么优雅。
这没有意义。你将如何在派生类的XXX中实现接口?没有理由你不能从实现中调用静态成员。 – leppie 2010-10-18 08:07:05
http://stackoverflow.com/questions/259026/why-doesnt-c-allow-static-methods-to-implement-an-interface – bernhof 2010-10-18 08:08:27
@leppie,你**可以**有一个“类型的方法”;那里没有隐含的'this',但它确实在运行时从该类型解析了方法。使用它们的罕见场合可以通过实例方法或反射来满足,所以不是迫切需要IMO。 – 2010-10-18 08:12:34