我正在編寫兩個API,我將與許多項目一起使用。有些項目使用了其中一個API,另一些則使用了其中一些,但我的大部分項目都將使用這兩個API。我試圖將它們設計成好像它們完全分開,但我在一件事上掙扎着。具有相同通用方法的抽象類和接口
namespace FirstApi {
public abstract class MyBaseClass {
//constructor, some methods and properties
public IEnumerable<T> Search<T>() where T : MyBaseClass, new() {
//search logic here. must use generics as I create new instances of T here
}
}
}
namespace SecondApi {
public interface IMyInterface {
//some property and method signatures
IEnumerable<T> Search<T>() where T : IMyInterface, new();
}
}
namespace MyProject {
public class MyDerivedClass : MyBaseClass, IMyInterface {
}
}
這兩個API都需要這種搜索方法。第二個API在調用IMyInterface.Search<T>()
的其他類中有一些功能,我希望那些繼承MyBaseClass
的類使用MyBaseClass
中定義的Search<T>
函數。
編譯錯誤:類型參數方法的「T」「MyBaseClass.Search()」的約束必須爲類型參數界面方法的「T」「IMyInterface.Search()」的約束條件相匹配。考慮使用顯式接口實現。
注意:當搜索被調用時,T將永遠是任何抽象類或接口已被繼承的派生類。這是我在C#2.0(C# abstract class return derived type enumerator)中實現這一目標的唯一方法,它只是造成了更多問題!
有沒有一種類型安全的方式,我可以實現這一點,而不使用對象和鑄造?
解決方案:基於由安德拉斯·佐爾坦接受的答案
,我在我的項目創造了這個班,並且將不得不重新創建這個類爲使用這兩個API每個項目。
public abstract class ApiAdapter<TAdapter> : MyBaseClass, IMyInterface where TAdapter: MyBaseClass, IJsonObject, new()
{
IEnumerable<T> IJsonObject.Search<T>()
{
foreach (TAdapter row in base.Search<TAdapter>())
yield return (T)(IMyInterface)row;
}
}
然後我就像這樣繼承這個類。
public class Client : ApiAdapter<Client> {
//everything else can go here
}
也許它在清晨,我都還沒有甦醒過來,但我不明白問題是什麼。爲什麼你提供的代碼不工作? – 2011-05-25 09:11:29
對不起,我更新了編譯器錯誤的帖子 – Connell 2011-05-25 09:16:46
對不起,我也不明白這個問題。也許提供一個真實世界的例子,而不是'IMyInterface'和'MyBaseClass'可以提供幫助。 – 2011-05-25 09:17:00