Home
Browsez les 647 exemples
Téléchargez les 647 exemples
Téléchargez des chapitres
Achetez sur amazon.fr

Niveau: Débutant/Intermédiaire
ISBN-2-84177-339-6
50 Euros

Exemple 13-40 extrait du chapitre La généricité


Exemple 13-39<     > Exemple 13-41


Cet exemple peut être compilé avec la ligne de commande:
csc.exe /target:exe Exemple_13_40.cs
Erreurs: 0 Avertissements: 0
Remarque:


Exemple_13_40.cs
using System;
using System.Reflection;
class Program {
   static void WriteTypeConstraints(Type type ){
      string[] results = new string[type.GetGenericArguments().Length];
      foreach (Type t in type.GetGenericArguments()) {
         if ( t.IsGenericParameter ) {
            int pos = t.GenericParameterPosition;
            Type[] derivConstraints = 
                        t.GetGenericParameterConstraints();
            MethodBase methodBase = t.DeclaringMethod;
            GenericParameterAttributes attributes = 
                        t.GenericParameterAttributes;
            results[pos] = "   where " + t.Name + ":";
            if ((GenericParameterAttributes.ReferenceTypeConstraint &
                 attributes) != ) {
               results[pos] += "class,";
            }
            if((GenericParameterAttributes.
                NotNullableValueTypeConstraint & attributes) != ) {
               results[pos] += "struct,";
            }
            foreach (Type derivConstraint in derivConstraints) {
               results[pos] += derivConstraint.Name + ",";
            }
            if ((GenericParameterAttributes.
                 DefaultConstructorConstraint & attributes) != ) {
               results[pos] += "new()";
            }
         }
      }
      Console.WriteLine(type.Name);
      foreach (string result in results)
         if (result != null)
            Console.WriteLine(result);
   }
   class Bar{}
   class Foo : BarIDisposablepublic void Dispose() {} }
   class C<U, V>
       where U : BarIDisposablenew()
       where V : struct {}

   static void Main() {
      WriteTypeConstraints( typeof(C<Foo,int>) );
      WriteTypeConstraints(
              typeof(C<Foo,int>).GetGenericTypeDefinition() );
   }
}	
Copyright Patrick Smacchia 2006 2007