Guide to the Language
Download 2 Mb. Pdf ko'rish
|
C sharp
- Bu sahifa navigatsiya:
- Generic Type Parameters
- Default Value
Calling Generic Methods
The generic method is now finished. To call it, the desired type argument needs to be specified in angle brackets before the method arguments. int a = 0, b = 1; Swap In this case, the generic method may also be called as if it were a regular method, without specifying the type argument. This is because the compiler can automatically determine the type since the generic method’s parameters use the type parameter. However, if this was not the case, or to use another type argument than the one the compiler would select, the type argument would then need to be explicitly specified. Chapter 28 GeneriCs 161 Swap(ref a, ref b); Whenever a generic is called for the first time during runtime, a specialized version of the generic will be instantiated that has every occurrence of the type parameter substituted with the specified type argument. It is this generated method that will be called and not the generic method itself. Calling the generic method again with the same type argument will reuse this instantiated method. Swap Swap When the generic method is called with a new type, another specialized method will be instantiated. long c = 0, d = 1; Swap Generic Type Parameters A generic can be defined to accept more than one type parameter just by adding more of them between the angle brackets. Generic methods can also be overloaded based on the number of type parameters that they define. static void Dummy static void Dummy Chapter 28 GeneriCs 162 Default Value When using generics, one issue that may arise is how to assign a default value to a type parameter since this value depends on the type. The solution is to use the default keyword followed by the type parameter enclosed in parentheses. This expression will return the default value no matter which type parameter is used. static void Reset { a = default(T); } Default expressions were enhanced in C# 7.1. As of this version, the type supplied to default may be omitted when the compiler can infer the type based on the context. static void Reset { a = default; // same as default(T) } Download 2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling