那麼,我相信它應該允許在泛型類型參數的情況下。它可能簡化合同單身班。下面是一個例子:
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