Csharp/C Sharp/Generics/Generic Type

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

A generic class with two generic parameters

<source lang="csharp"> using System; using System.Collections.Generic; using System.Text;

class MyCache<K, V> {

   private static Dictionary<K, V> _objectCache;
   public MyCache() {
       MyCache<K, V>._objectCache = new Dictionary<K, V>();
   }
   private V FindValueInDB(K key) {
       return default(V);
   }
   public V LookupValue(K key) {
       V retVal;
       if (_objectCache.ContainsKey(key) == true) {
           _objectCache.TryGetValue(key, out retVal);
       } else {
           retVal = FindValueInDB(key);
       }
       return retVal;
   }

} class MyApp {

   public static void main(String[] args) {
       MyCache<string, string> cache1 = new MyCache<string, string>();
       string val1 = cache1.LookupValue("key1");
       MyCache<string, int> cache2 = new MyCache<string, int>();
       int val2 = cache2.LookupValue("key1");
   }

}

       </source>


A generic Point structure.

<source lang="csharp"> using System; using System.Collections.Generic; using System.Text; public struct Point<T> {

   private T xPos;
   private T yPos;
   public Point(T xVal, T yVal) {
       xPos = xVal;
       yPos = yVal;
   }
   public T X {
       get { return xPos; }
       set { xPos = value; }
   }
   public T Y {
       get { return yPos; }
       set { yPos = value; }
   }
   public override string ToString() {
       return string.Format("[{0}, {1}]", xPos, yPos);
   }
   public void ResetPoint() {
       xPos = default(T);
       yPos = default(T);
   }

}

</source>


Call ToString on generic type

<source lang="csharp">

using System; using System.Collections.Generic; using System.Text; public class HelloGenerics<T> {

   private T _thisTalker;
   public T Talker {
       get { return this._thisTalker; }
       set { this._thisTalker = value; }
   }
   public void SayHello() {
       string helloWorld = _thisTalker.ToString();
       Console.WriteLine(helloWorld);
   }

} public class GermanSpeaker {

   public override string ToString() {
       return "GermanSpeaker!";
   }

} public class SpainishSpeaker {

   public override string ToString() {
       return "SpainishSpeaker";
   }

} public class EnglishSpeaker {

   public override string ToString() {
       return "EnglishSpeaker";
   }

} class Program {

   static void Main(string[] args) {
       HelloGenerics<GermanSpeaker> talker1 = new HelloGenerics<GermanSpeaker>();
       talker1.Talker = new GermanSpeaker();
       talker1.SayHello();
       HelloGenerics<SpainishSpeaker> talker2 = new HelloGenerics<SpainishSpeaker>();
       talker2.Talker = new SpainishSpeaker();
       talker2.SayHello();
   }

}

       </source>


combining inheritance of generic types and constraints:

<source lang="csharp"> using System; using System.Collections; public class MyClass<T> where T : IComparable { } public class YClass<T> : MyClass<T> where T : IComparable { } public class XClass<T> : MyClass<T> where T : IComparable, IDisposable { } public class BClass<Y> where Y : IEnumerable { } public class AClass<Z> : BClass<int[]> where Z : IDisposable { }

</source>


Deserialize generic type

<source lang="csharp">

   using System;
   using System.Runtime.Serialization;
   using System.Runtime.Serialization.Formatters.Binary;
   using System.IO;
   public class Test{
       public static void Main(string [] args){
           BinaryFormatter binary=new BinaryFormatter();
           FileStream file= new FileStream("test.dat", FileMode.OpenOrCreate);
           MyGenericClass<int> obj1=(MyGenericClass<int>)
           binary.Deserialize(file);
           Console.WriteLine(obj1.GetValue());
       }
   }
   [Serializable] 
   public class MyGenericClass<T> {
       public MyGenericClass(T init) {
           fielda=init;
       }
       public void GetObjectData(SerializationInfo info,StreamingContext ctx) {
           info.AddValue("fielda", fielda, typeof(T));
       }
       private MyGenericClass(SerializationInfo info, StreamingContext ctx) {
           fielda=(T) info.GetValue("fielda", typeof(T));
       }
       public void SetValue(T data) {
          fielda=data;
       }
       public T GetValue() {
          return fielda;
       }
       private T fielda=default(T);
   }
          
      </source>


Inherit Type Parameter

<source lang="csharp">

using System; using System.Collections.Generic; using System.Text; public class MyBaseClass {

   private U _parentData;
   public MyBaseClass() { }
   public MyBaseClass(U val) {
       this._parentData = val;
   }

} public class MySubClass<T, U> : MyBaseClass<U> {

   private T _myData;
   public MySubClass() { }
   public MySubClass(T val1, U val2)
       : base(val2) {
       this._myData = val1;
   }

}

         </source>


Nested generic Types

<source lang="csharp">

   using System;
   public class Test{
       public static void Main(){
           Z<int>.Nested<double> obj= new Z<int>.Nested<double>();
           obj.MethodA(10, 12.34);
       }
   }
   public class Z<T> {
       public void MethodA(T arg) {
       }
       public class Nested<S> {
           public void MethodA(T arg1, S arg2) {
               Console.WriteLine("arg1: {0}", arg1.GetType().ToString());
               Console.WriteLine("arg2: {0}", arg2.GetType().ToString());
           }
       }
   }
          
         </source>


Nested Types

<source lang="csharp">

using System; public class Starter {

   public static void Main() {
       MyClass<int>.Nested<double> obj =
           new MyClass<int>.Nested<double>();
       obj.MethodA(10, 12.34);
   }

} public class MyClass<T> {

   public void MethodA(T arg) {
   }
   public class Nested {
       public void MethodA(T arg1, S arg2) {
           Console.WriteLine("arg1: {0}",
               arg1.GetType().ToString());
           Console.WriteLine("arg2: {0}",
               arg2.GetType().ToString());
       }
   }

}

</source>


Output the type information about the generic parameters

<source lang="csharp">

using System; using System.Collections.Generic; using System.Text; public class OneParamType<T> {} public class TwoParamType<T, U> {} public class TypeDumper<T, U, V> {

   public static void DumpTypeInfo() {
       Console.WriteLine(typeof(T));
       Console.WriteLine(typeof(U));
       Console.WriteLine(typeof(V));
       Console.WriteLine(typeof(OneParamType<String>));
       Console.WriteLine(typeof(OneParamType<T>));
       Console.WriteLine(typeof(TwoParamType<U, int>));
       Console.WriteLine(typeof(TwoParamType<T, V>));
   }
   public static void ShowTypeInfo() {
       TypeDumper<String, int, Double>.DumpTypeInfo();
   }    

}

         </source>


Reference for Generic Types

<source lang="csharp"> using System; public class Starter {

   public static void Main() {
       MyClass<int> obj = new MyClass<int>();
       obj.MethodA();
   }

} class MyClass<T> {

   public T MethodA() {
       T var = default(T);
       Console.WriteLine(this.GetType().ToString());
       return var;
   }

}

</source>


Serialization for generic type

<source lang="csharp">

   using System;
   using System.Runtime.Serialization;
   using System.Runtime.Serialization.Formatters.Binary;
   using System.IO;
   public class Test{
       public static void Main(string [] args){
           BinaryFormatter binary=new BinaryFormatter();
           FileStream file= new FileStream("test.dat", FileMode.OpenOrCreate);
           MyGenericClass<int> obj=new MyGenericClass<int>(5);
           binary.Serialize(file, obj);
       }
   }
   [Serializable] 
   public class MyGenericClass<T> {
       public MyGenericClass(T init) {
           fielda=init;
       }
       public void GetObjectData(SerializationInfo info,StreamingContext ctx) {
           info.AddValue("fielda", fielda, typeof(T));
       }
       private MyGenericClass(SerializationInfo info, StreamingContext ctx) {
           fielda=(T) info.GetValue("fielda", typeof(T));
       }
       public void SetValue(T data) {
          fielda=data;
       }
       public T GetValue() {
          return fielda;
       }
       private T fielda=default(T);
   }
          
      </source>