Csharp/CSharp Tutorial/Generic/where

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

Generic Operator Overloading

using System;
using System.ruponentModel;
    class OperatorOverloading
    {
        static bool AreReferencesEqual<T>(T first, T second)
            where T : class
        {
            return first == second;
        }
        static void Main()
        {
            string name = "J";
            string intro1 = "My name is " + name;
            string intro2 = "My name is " + name;
            Console.WriteLine(intro1 == intro2);
            Console.WriteLine(AreReferencesEqual(intro1, intro2));
        }
    }

Use multiple where clauses

Gen has two type arguments and both have a where clause.


using System; 
 
class Gen<T, V> where T : class 
                where V : struct {  
  T ob1;  
  V ob2;  
 
  public Gen(T t, V v) { 
    ob1 = t; 
    ob2 = v; 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    Gen<string, int> obj = new Gen<string, int>("test", 11); 
 
    // wrong because bool is not a reference type. 
    // Gen<bool, int> obj = new Gen<bool, int>(true, 11); 
         
  } 
}

where T: struct

using System.Collections.Generic;
public class MyValueList<T> where T: struct
{
    private List<T> imp = new List<T>();
    
    public void Add( T v ) {
        imp.Add( v );
    }
}
public class MainClass
{
    static void Main() {
        MyValueList<int> intList = new MyValueList<int>();
        intList.Add( 123 );
        // CAN"T DO THIS.
        // MyValueList<object> objList = new MyValueList<object>();
    }
}