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) != 0 ) {
results[pos] += "class,";
}
if((GenericParameterAttributes.
NotNullableValueTypeConstraint & attributes) != 0 ) {
results[pos] += "struct,";
}
foreach (Type derivConstraint in derivConstraints) {
results[pos] += derivConstraint.Name + ",";
}
if ((GenericParameterAttributes.
DefaultConstructorConstraint & attributes) != 0 ) {
results[pos] += "new()";
}
}
}
Console.WriteLine(type.Name);
foreach (string result in results)
if (result != null)
Console.WriteLine(result);
}
class Bar{}
class Foo : Bar, IDisposable{ public void Dispose() {} }
class C<U, V>
where U : Bar, IDisposable, new()
where V : struct {}
static void Main() {
WriteTypeConstraints( typeof(C<Foo,int>) );
WriteTypeConstraints(
typeof(C<Foo,int>).GetGenericTypeDefinition() );
}
}
Copyright Patrick Smacchia 2006 2007
|