Csharp/CSharp Tutorial/Generic/where — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 18:31, 26 мая 2010
Generic Operator Overloading
<source lang="csharp">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)); } }</source>
Use multiple where clauses
Gen has two type arguments and both have a where clause.
<source lang="csharp">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); }
}</source>
where T: struct
<source lang="csharp">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>(); }
}</source>