Console.WriteLine (intEcho.IsGenericMethodDefinition); Console.WriteLine (intEcho.Invoke (null, new object[] { 3 } ));
// False // 3
Reflection is useful when you need to invoke a member of a generic interface and you don’t know the type parameters until runtime. In theory, the need for this arises rarely if types are perfectly designed; of course, types are not always perfectly designed. For instance, suppose we want to write a more powerful version of ToString that could expand the result of LINQ queries. We could start out as follows: public static string ToStringEx <T> (IEnumerable<T> sequence) { ... }
This is already quite limiting. What if sequence contained nested collections that we also want to enumerate? We’d have to overload the method to cope: public static string ToStringEx <T> (IEnumerable<IEnumerable<T>> sequence)
And then what if sequence contained groupings, or projections of nested sequences? The static solution of method overloading becomes impractical—we need an approach that can scale to handle an arbitrary object graph, such as the following: public static string ToStringEx (object value) { if (value == null) return "<null>"; StringBuilder sb = new StringBuilder(); if (value is List<>) sb.Append ("List of " + ((List<>) value).Count + " items");
// Error // Error
if (value is IGrouping<,>) sb.Append ("Group with key=" + ((IGrouping<,>) value).Key);
// Error // Error
// Enumerate collection elements if this is a collection, // recursively calling ToStringEx() // ... }
return sb.ToString();
Unfortunately, this won’t compile: you cannot invoke members of an unbound generic type such as List<> or IGrouping<>. In the case of List<>, we can solve the problem by using the nongeneric IList interface instead: if (value is IList) sb.AppendLine ("A list with " + ((IList) value).Count + " items");
Reflecting and Invoking Members | 783
Reflection
Anonymously Calling Members of a Generic Interface
List of 3 items: 5 6 7 Group with key=x: x Group with key=y: y y Group with key=z: z z z
myReflectionOnlyType
XXX
...
Group with key=x: x Group with key=y: y y Group with key=z: z z z
Method , ,
Property or field Indexer Unary operator such as Binary operator such as Conversion (cast) to another type Invocation on the object itselfâ&#x20AC;&#x201D;e.g.,
someDbCommand
Advanced operations, such as calling unmanaged code Use of reflection Reading/writing command-line environment settings Reading or writing to the Windows Registry
Reading/writing files and directories Reading/writing to a file chosen through an Open or Save dialog box Reading/writing to own isolated storage Reading of application configuration files ,
,
Communicating with a database server using the , , or class Participation in distributed transactions
DNS lookup -based network access -based network access Sending mail through the SMTP libraries Use of classes such as
and
Use of the Windows data protection methods Public key encryption and signing Access to X.509 certificate stores
Creating windows and interacting with the clipboard Use of the
control
Image, audio, and video support in WPF Accessing a printer
Reading or writing to the Windows event log Use of Windows performance counters
The assembly is loaded into the GAC The calling assembly has a particular strong name The calling assembly is Authenticode-signed with a particular certificate
ps
0
Fast
Depends on user’s password
Protects files transparently with filesystem support. A key is derived implicitly from the logged-in user’s credentials.
Windows Data Protection
0
Fast
Depends on user’s password
Encrypts and decrypts byte arrays using an implicitly derived key.
Hashing
0
Fast
High
One-way (irreversible) transformation. Used for storing passwords, comparing files, and checking for data corruption.
Symmetric Encryption
1
Fast
High
For general-purpose encryption/decryption. The same key encrypts and decrypts. Can be used to secure messages in transit.
Public Key Encryption
2
Slow
High
Encryption and decryption use different keys. Used for exchanging a symmetric key in message transmission and for digitally signing files.
mscorlib.dll
(always)
XXX
XXX
XXX
Share lock
Read lock
Exclusive lock
Write lock
Update lock
Upgradeable lock
(pause)
Lazily
enabled DoSomeAction
PLINQ
Yes
Yes
class
Yes
No
PFXâ&#x20AC;&#x2122;s task parallelism
No
No
The
.QueryOperator1 .QueryOperator2 QueryOperator3
Chunk partitioning
Dynamic
Average
Range partitioning
Static
Poor to excellent
Hash partitioning
Static
Poor
For managing a unit for work For managing a unit for work with a return value For creating tasks For creating tasks and continuations with the same return type For managing the scheduling of tasks For manually controlling a taskâ&#x20AC;&#x2122;s workflow
someSequence enumerate query
(none)
block end
XXX
XXX
XXX
Ignores case (by default, regular expressions are case-sensitive) Changes and so that they match the start/end of a line instead of start/end of the string Captures only explicitly named or explicitly numbered groups (see “Groups” on page 1000) Forces compilation of regular expression to IL Makes match every character (instead of matching every character except ) Eliminates unescaped whitespace from the pattern Searches from right to left; can’t be specified midstream Forces ECMA compliance (by default, the implementation is not ECMA-compliant) Turns off culture-specific behavior for string comparisons
Matches a single character in the list Matches a single character in a range Matches a decimal digit Same as Matches a word character (by default, varies according to ; for example, in English, same as Matches a whitespace character Same as category
Matches a character in a specified category (Default mode) Matches any character except (
mode) Matches any character
)
Zero or more matches One or more matches Zero or one match n
Exactly n matches
n
At least n matches
n m
Between n and m matches
expr
OUTPUT: 25
expr
expr expr
expr expr
OUTPUT: a.txt c.txt
Wedding In Sarajevo
group-name
group-name
or
or
group-name
OUTPUT: catapult the dog
group-name
OUTPUT: <10> plus <20> makes <30>
name
OUTPUT: 50 is less than 100
id is 3 secure is true timeout is 30
01/02/2008 5:20:50 PM 01 02 2008 5 20 50 PM
In the beginning
My good recipes.txt
Bell Backspace Tab Carriage return Vertical tab Form feed Newline Escape nnn nn
ASCII character nnn as octal (e.g., ASCII character nn as hex (e.g.,
) )
l
ASCII control character l (e.g.,
for Ctrl-G)
nnnn
Unicode character nnnn as hex (e.g.,
)
A nonescaped symbol
symbol
Matches a single character in the list Matches a single character in a range Matches a decimal digit Same as Matches a word character (by default, varies according to ; for example, in English, same as ) Matches a whitespace character Same as category
Matches a character in a specified category (see Table 26-6) (Default mode) Matches any character except (
Letters Uppercase letters Lowercase letters Numbers Punctuation Diacritic marks Symbols Separators Control characters
mode) Matches any character
Zero or more matches One or more matches Zero or one match n
Exactly n matches
n
At least n matches
n,m
Between n and m matches
Substitutes the matched text group-number group-name
Substitutes an indexed group-number within the matched text Substitutes a text group-name within the matched text
Start of string (or line in multiline mode) End of string (or line in multiline mode) Start of string (ignores multiline mode) End of string (ignores multiline mode) End of line or string Where search started On a word boundary Not on a word boundary expr
Continue matching only if expression expr matches on right (positive lookahead)
expr
Continue matching only if expression expr doesnâ&#x20AC;&#x2122;t match on right (negative lookahead)
expr
Continue matching only if expression expr matches on left (positive lookbehind)
expr
Continue matching only if expression expr doesnâ&#x20AC;&#x2122;t match on left (negative lookbehind)
expr
Subexpression expr is matched once and not backtracked
Capture matched expression expr into indexed group
expr
Capture matched substring into a specified group number
number name
Capture matched substring into group name
name1-name2
Undefine name2, and store interval and current group into name1; if name2 is undefined, matching backtracks; name1 is optional
expr
Noncapturing group
Reference a previously captured group by index
index
Reference a previously captured group by name
name
Logical or expr yes no
Matches yes if expression matches; otherwise, matches no (no is optional)
name yes no
Matches yes if named group has a match; otherwise, matches no (no is optional)
comment comment
Inline comment Comment to end of line (works only in
Case-insensitive match (“ignore” case) Multiline mode; changes and so that they match beginning and end of any line Captures only explicitly named or numbered groups Compiles to IL Single-line mode; changes meaning of “.” so that it matches every character Eliminates unescaped whitespace from the pattern Searches from right to left; can’t be specified midstream
mode)
∞
∞
Joseph Albahari
Ben Albahari