在C#中實現多種類型對象的堆棧的最佳方法是什么?

[英]What is the best way of implementing a stack of more than one type of object in C#?


I'm writing an implementation of a virtual machine in C#, and I need to implement the VM's stack, which can contain two types of entry - return entries or backtrack entries. What is the best way of implementing this?

我正在用C#編寫虛擬機的實現,我需要實現VM的堆棧,它可以包含兩種類型的入口 - 返回條目或回溯條目。實現這個的最佳方法是什么?

I'm currently using a base type, as follows:

我目前正在使用基類型,如下所示:

class StackEntry { }
class Return : StackEntry { uint pc; }
class Backtrack : StackEntry { uint pc; object backtrack; }

Stack<StackEntry> stack;

This works OK, but the resulting type testing and downcasting feels clumsy.

這樣工作正常,但最終的類型測試和向下轉換感覺很笨拙。

Is there a better way of handling this type of construction?

有沒有更好的方法來處理這種類型的建築?

4 个解决方案

#1


6  

I'm having a hard time imagining how you're going to use this, but the basic answer is that you use a single type with a default operation for post-pop processing

我很難想象你將如何使用它,但基本的答案是你使用一個默認操作的單一類型進行后期處理

StackEntry { protected virtual void PostPop(); }
Return : StackEntry { protected override void PostPop(); }
Backtrack : StackEntry { protected override void PostPop(); }

Does that make sense?

那有意義嗎?

#2


3  

What's wrong with putting the BackTrack object in anyway and have it be null if there is no back track? You can add a helpful property like bool IsBacktrack { get { return _backTrack != null; } }

無論如何將BackTrack對象放入並且如果沒有回溯,它是否為空?您可以添加一個有用的屬性,如bool IsBacktrack {get {return _backTrack!= null; }}

Can the backtrack be validly null? If yes, then use a bool flag for it.

回溯可以有效地為空嗎?如果是,則使用bool標志。

#3


2  

Why should you need to down cast? If your base class exposes abstract or virtual members, or is instead an interface, you should have no problem. This principle is the foundation of OOP.

為什么你需要投球?如果您的基類公開抽象或虛擬成員,或者是一個接口,那么您應該沒有問題。這個原則是OOP的基礎。

If that doesn't work for you then you do a switch on myStack[x].GetType()

如果這對你不起作用,那么你可以在myStack上進行切換[x] .GetType()

#4


0  

It depends on the level of abstraction that you expect. The base class method is quite nice. Only when benchmarks reveal that too much performance is lost this way, I would try to drill deeper, perhaps using a custom-tailored structure with explicit memory layout that acts similar to a C union.

這取決於您期望的抽象級別。基類方法非常好。只有當基准測試顯示太多性能以這種方式丟失時,我才會嘗試更深入地鑽取,可能使用具有顯式內存布局的定制結構,其行為類似於C聯合。

How does your code affect usability in a negative way?

您的代碼如何以負面方式影響可用性?


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2008/11/04/e035e56fc2b9e9fa3522716303465faa.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com