![](/img/trans.png)
[英]C# - Serialize all attributes of derived class in a list of base class
[英]c# List of derived class
我正在開發用於工作的C#WinForm應用程序,但是我遇到了麻煩,我不知道哪一種是繼續進行的最佳方法。 這是一段代碼
class Block()
{
// generic Block properties
}
class ABlock() : Block
{
// specific ABlock stuff
}
class BBlock() : Block
{
// specific BBlock stuff
}
abstract class Algorithm()
{
// generic Algorithm properties
abstract List<Block> BlockList // ??
}
class AAlgorithm() : Algorithm
{
// specific AAlgorithm stuff
List<ABlock> BlockList // ??
}
class BAlgorithm() : Algorithm
{
// specific BAlgorithm stuff
List<ABlock> BlockList // ??
}
我認為情況非常簡單: Algorithm
每個派生類都有它自己的Block
派生類,但是我想使它通用,並且可以從asbtract class Algorithm
List<Block> BlockList
asbtract class Algorithm
中進行asbtract class Algorithm
。 我認為這是常見的情況,我敢肯定有解決方案。
提前致謝
我可能會丟失一些東西,但是您不能將其設為抽象屬性嗎?
abstract class Algorithm()
{
abstract List<Block> BlockList { get; }
}
...那么,當編寫一個從Algorithm派生的類時,除非實現BlockList.get,否則它將不會編譯:
public class AlgorithmA : Algorithm
{
public override List<Block> Blocks
{
get
{
return new List<Block> { new ABlock(), new ABlock() };
}
}
}
唯一的瑕疵是,如果AlgorithmA中的代碼想要使用Blocks屬性,則可能需要將其強制轉換為(ABlock)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.