开发者

Built-in Generic Types

I read somewhere that EventHandler is a built-in generic type. Why is that so? Could somebody explain me ways to distinguish between generic and non-generic types?

Thanks, Abhi.

================

I am reading Microsoft .NET Framework Application Development Foundation 2nd edition to prepare for MCTS. In the first cha开发者_开发技巧pter, there was a question as below:-

Which of the following are examples of built-in generic types? (Choose all that apply.) A. Nullable B. Boolean C. EventHandler D. System.Drawing.Point

The answer of the question is A and C as per the book. Option A is alright, but wasn't sure about option C. Can somebody please explain?


There are two types: EventHandler and EventHandler<TEventArgs>. Obviously the first isn't generic, and the second is.


To answer the question you ultimately need to look up each type name in the MSDN index. Nullable appears as Nullable<T>. EventHandler shows up twice, with and without the <T> suffix. These are in fact separate types.


T is the type of EventArgs the eventhanlder handles (so T : EventArgs)


In C# (but it applies to Java too), you can recognize generics by the presence of Type Parameters, usually indicated between <> brackets.

For example, the generic type of EventHandler in C# is declared as:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

The type TEventArgs that parameterises the delegate is used to have static typing inside the event handler function, without the need for casts or to define multiple delegate types for each type of argument you need passed to the handler.

Say you have 2 different events, one generating objects of type T1, one of type T2. You will have two different handlers:

void HandleEvent1(object sender, T1 args) {...}
void HandleEvent2(object sender, T2 args) {...}

In C# 1.0 (no generics) you would create your own delegate types for the 2 events:

delegate void Event1Handler(object sender, T1 e);
delegate void Event2Handler(object sender, T2 e);

And use them to bind your event with the handlers.

From C# 2.0 there's no need to create new delegate types, since both handlers are captured by the generic EventHandler<> type (TEventArgs = T1 or TEventArgs = T2).

See here and here for an intro on generics.


The question is badly phrased, but is asking which of the types are generic (or have generic versions). The answer is EventHandler and Nullable, since Boolean and Point do not have generic equivalents.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜