在STL.NET的设计中,STL的实现使用了CLI泛型和C++模版机制。2005版本的C++将加入C++/CLI动态编程的支持,应当会成为最能够满足程序员设计的语言。
给予程序员丰富的选择
总共有三个容器库可供程序员用于操作CLI类型,这三个容器库建于三种类型参数化模型之上。
原先元素类型存储的Systems::Collection 库是基于CLI类型中的对象基类来实现的。如下的 ArrayList实现了IList接口。它代表类型对象的数组,在本例中用于控制String类型的元素。(这里采用版本2的语法来实现)
void objectCollection() { using namespace System::Collections; ArrayList ^as = gcnew ArrayList; as->Add( "Pooh" ); as->Add( "Piglet" ); as->Add( "Eeyore" ); as->Add( "Rabbit" ); as->Sort(); Console::WriteLine( "ArrayList holds {0} elements: ",as->Count ); for ( int i = 0; i < as->Count; i++ ) Console::WriteLine( as[ i ] ); int index = as->IndexOf( "Pooh" ); if ( index != -1 ) { //需要一个清晰地downcast String^ item = safe_cast( as[ index ]); as->RemoveAt( index ); } as->Remove( "Rabbit" ); Console::WriteLine( "\nArrayList holds {0} elements: ",as->Count ); IEnumerator^ is = as->GetEnumerator(); while ( is->MoveNext() ) Console::WriteLine( is->Current ); } |
#include #include void stlCollection() { vector ^svec = gcnew vector; svec->push_back("Pooh"); svec->push_back("Piglet"); svec->push_back("Eeyore"); svec->push_back("Rabbit"); //泛型算法:sort sort( svec->begin(), svec->end() ); Console::WriteLine( "Collection holds {0} elements: ",svec->size() ); for ( int i = 0; i < svec->size(); i++ ) Console::WriteLine( svec[ i ] ); //泛型算法:find vector::iterator iter = find( svec->begin(), svec->end(), "Pooh" ); if ( iter != svec->end() ) { //不需要downcast…… String ^item = *iter; svec->erase( iter ); } //泛型算法: remove…… remove( svec->begin(), svec->end(), "Rabbit" ); Console::WriteLine( "\nCollection holds {0} elements:",svec->size() ); IEnumerator ^is = svec->GetEnumerator(); while ( is->MoveNext() ) Console::WriteLine( is->Current ); } |
共4页: 1 [2] [3] [4] 下一页 |