[英]C# Interface<T> { T Func<T>(T t);} : Generic Interfaces with Parameterized Methods with Generic Return Types
我想我會使用一些(我認為是)簡單的泛型來在某些業務類上強制執行 CRUD。 例如。
public interface IReadable <T>
{
T Read<T>(string ID);
}
然后也許,我可以有一個 NoteAdapter 來使用 Note 類來執行 C R UD,例如。
public class NoteAdapter : IReadable<Note>
{
public Note Read<Note>(string ID) {
return new Note();
}
}
但是出於某種原因,如果我同時擁有泛型返回類型和使用相同泛型類型參數化的函數,則編譯器會感到困惑。 也就是說,如果我這樣做:
public interface IReadable <T>
{
void Read<T>(string ID);
}
public class NoteAdapter : IReadable<Note>
{
public void Read<Note>(string ID) {
return new Note();
}
}
它編譯得很好,雖然它沒有做我想要的! 另外,這個:
public interface IReadable <T>
{
T Read (string ID);
}
public class NoteAdapter : IReadable<Note>
{
public Note Read(string ID) {
return new Note();
}
}
工作正常,雖然它也不能滿足要求! - 為什么 ? 因為那樣我就不能有一個實現一堆這些接口的類......例如。
public interface IReadable <T>{
T Read (string ID);
}
public class UniversalAdapter : IReadable<Note>, IReadable<Customer> ...
{
public Note Read(string ID) {
return new Note();
}
public Customer Read(string ID) {
return new Customer();
}
}
因為這不會編譯,因為返回類型不是方法簽名的一部分!
我的印象是,在 C# 3.5 +
T Foo(T t);
T Foo<T> (T t);
T Foo(<SomeType> someInstance);
每個人都有不同的簽名! 我在這里錯過了什么?
你過度指定了接口。 您在接口定義中聲明了T
,但隨后在方法的定義中重新聲明了它:
public interface IReadable <T> /* T is declared here */
{
T Read<T>(string ID); /* here, you've declare a NEW generic type parameter */
/* that makes this T not the same as the T in IReadable */
}
由於這種混淆,當您嘗試實現接口時最終會出現錯誤。
public class NoteAdapter : IReadable<Note> /* IReadable defines T to be Note */
{
public Note Read<Note>(string ID) { /* Here, you're declaring a generic parameter */
/* named Note. This name then conflicts with */
/* the existing type name Note */
return new Note();
}
}
要解決此問題,您只需從接口和NoteAdapter
類中的Read
函數中刪除泛型參數:
public interface IReadable <T>
{
T Read(string ID);
}
public class NoteAdapter : IReadable<Note>
{
public Note Read(string ID) {
return new Note();
}
}
編輯:
好的,我閱讀了您的其余帖子,似乎您已經發現這“有效”,但您似乎認為這是不正確的。 為什么? 這不符合什么要求?
public interface IReadable <T> { T Read<T>(string ID); }
這里真的有兩個不同的 Ts : IReadable <T> and T Read<T>(string ID)
也許只是
public interface IReadable <T> { T Read(string ID); }
public interface IReadable <T> { T Read(string ID); }
?
因為否則等於
public interface IReadable <T> { X Read<X>(string ID); }
編輯:
可能你需要public interface IReadable <T> { T Read(T ID); }
public interface IReadable <T> { T Read(T ID); }
?
CIL 不支持按返回類型重載方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.