Home
Browse all 647 examples
Download all 647 examples
Download sample chapters
Reviews
Errata
Acknowledgments
Links on .NET
Paradoxal Press
Buy directly from Paradoxal Press at $33.99 (Save 43%)
Category: Programming
Level: Beginner to seasoned
900 pages
ISBN-10 097661322-0
ISBN-13 978-097661322-0
$59.99 USA
$79.99 CANADA
|
Listing 13-40 extracted from chapter
Generics
Listing 13-39< > Listing 13-41
This listing can be compiled with the command line: csc.exe /target:exe Example_13_40.cs Errors: 0 Warnings: 0
Example_13_40.cs
using System;
using System.Reflection;
class Program {
static void WriteTypeConstraints(Type type ){
string[] results = new string[type.GetGenericArguments().Length];
// For each parameter types.
foreach (Type t in type.GetGenericArguments()) {
// If 't' is a parameter type not specified?
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()";
}
} // end -- If 't' is a parameter type not specified?
} // end -- For each parameter types.
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
|