Visual C++ .NET/Generics/Generic Class

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Generic class definition

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; using namespace System::Collections;

generic<typename T> ref class MyClass { public:

   MyClass(int N)
   {
       m_Array = gcnew array<T>(N);
   }
   static MyClass()
   {
       Console::WriteLine("static constructor");
   }
   void SetItem(int i, T t)
   {
       m_Array[i] = t;
   }
   T GetItem(int i)
   {
       return m_Array[i];
   }
   String^ GetItemStringValue(int i)
   {
       return m_Array[i]->ToString();
   }

private:

   array<T>^ m_Array;

};

void main() {

 MyClass<String^>^ myClass = gcnew MyClass<String^>(10);
 myClass->SetItem(0, "test");
 Console::WriteLine("{0}", myClass->GetItem(0));
     // Value class specialization
 MyClass<DateTime>^ myClass2 = gcnew MyClass<DateTime>(10);
 myClass2->SetItem(0, DateTime::Today);
 Console::WriteLine("{0}", myClass2->GetItem(0));

}

 </source>


Generic Class Demo

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; generic<class K, class V> where K : IComparable ref class KVClass{ public:

   property K Key;
   property V Value;
   KVClass(K key, V value);
   V isGreater(KVClass ^in);

}; generic<class K, class V> KVClass<K,V>::KVClass(K key, V value) {

   Key = key;
   Value = value;

}

generic<class K, class V>where K : IComparable V KVClass<K,V>::isGreater(KVClass ^in){

   if (Key->CompareTo(in->Key) > 0)
       return Value;
   else
       return in->Value;

} void main(){

   KVClass<int,String^> ^a = gcnew KVClass<int,String^>(5, "Five");
   KVClass<int,String^> ^b = gcnew KVClass<int,String^>(6, "Six");
   Console::WriteLine(a->isGreater(b));
   KVClass<String^,int> ^t = gcnew KVClass<String^,int>("A", 1);
   KVClass<String^,int> ^c = gcnew KVClass<String^,int>("B", 2);
   Console::WriteLine(t->isGreater(c));

}

 </source>


Generic class for value type

<source lang="csharp">

  1. include "stdafx.h"

using namespace System; generic <typename T> ref class GenericClass {

  T t;
  public:
     GenericClass() {}
     property T InnerValue
     {
         T get() { return t; }
         void set(T value) { t = value; }
     }

}; int main() {

  double d = 0.01;
  int n = 12;
  GenericClass<double>^ r_double = gcnew GenericClass<double>();
  GenericClass<int>^ r_int = gcnew GenericClass<int>();
  r_double->InnerValue = d;
  r_int->InnerValue = n;
  Console::WriteLine( r_double->InnerValue );
  Console::WriteLine( r_int->InnerValue );

}

 </source>