我找到了以下示例,對此我有一個后續問題。

如果所有具體類之間存在共享邏輯,則可以將其放在抽象類中并覆寫抽象受保護方法。
編輯: 操作要求可以做到這一點的代碼..這應該可以作業..但是如果你想要一個新的具體實作,你現在必須創建2個類
public class BarRepository<T> : RepositoryBase<T> where T : Bar
{
public override int Add(T item)
{
throw new NotImplementedException();
}
public override int Update(T item)
{
throw new NotImplementedException();
}
public override int Delete(T item)
{
throw new NotImplementedException();
}
}
public class BarRepository : BarRepository<Bar>
{
}
另外,如果類是如此相似以至于復制粘貼和替換就足夠了,那么邏輯可能不應該在單獨的類中而是在泛型類中?你能舉一個2類的例子嗎?
編輯 2:另一個骯臟的技巧是使用 lambdas,雖然我個人不知道我是否會這樣做:
public abstract class RepositoryBase<T>
{
public Func<T, int> Add { get; protected set; }
public Func<T, int> Update { get; protected set; }
public Func<T, int> Delete { get; protected set; }
}
public class BarRepository : RepositoryBase<Bar>
{
public BarRepository()
{
Add = i => 6;
Update = i => 7;
Delete = i => 8;
}
}
uj5u.com熱心網友回復:
這有點 hack,但您可以使用using別名來定義物體型別:
using MyType = Bar;
public class BarRepository : Repositorybase<MyType>
{
public override RepositoryInstructionResult Update(MyType item);
{
return base.Update(item);
}
}
現在,當您復制到時Foo.cs,您只需將 using 指令更改為
using MyType = Foo;
但是,我會嘗試盡可能多地重用通用代碼,因為MyType僅僅通過查看方法根本不清楚什么是。find.replace 定義自定義操作的新存盤庫型別沒有任何問題 - 您只想將重復保持在最低限度。
uj5u.com熱心網友回復:
恕我直言,任何 GENERIC 存盤庫都是浪費時間,但是如果您決定使用它,這有什么問題
public class BarRepository<T> : Repository<Bar> where T : class
{
public override void Update(Bar item)
{
}
public void Update(T item)
{
}
}
更新
它看起來很奇怪,但既然 OP 想要它,你也可以創建這個代碼
public class BarRepository<T> : Repository<Bar> where T : Bar
{
public override void Update(Bar item)
{
Console.WriteLine("it is Bar");
}
// T is of Type Bar
public void Update(T item)
{
Console.WriteLine("it is T");
}
}
測驗
public class Bar { }
public class NoBar { }
var barRep= new BarRepository<Bar>();
barRep.Update(new Bar()); // "it is T"
var noBarRep= new BarRepository<NoBar>(); // ERROR!
更新 2
因為如果你想
var rep = new BarRepository();
var result= rep.Update(new Bar());
你可以按照你已經做過的方式去做
public class BarRepository : Repositorybase<Bar>
{
public override RepositoryInstructionResult Update(Bar item);
{
return base.Update(item);
}
}
附言
如果您仍然不滿意,請查看我的答案的開頭并忘記通用存盤庫。像最專業的開發人員一樣使用定制的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/415121.html
標籤:
