- Beginning C# 7 Hands-On:Advanced Language Features
- Tom Owsiak
- 392字
- 2021-07-02 15:29:15
Accumulating the input
Now, we will accumulate the input. So, in the following sampLabel.Text lines, we change the = sign to +=, as shown here:
GenericsClass<double> dubs = new GenericsClass<double>(new double[] { 1.0, -2.3, 3, 4, 5 });
sampLabel.Text += ints.DisplayValues();
GenericsClass<decimal> decs = new GenericsClass<decimal>(new decimal[] { 1, 2.0M, 3, 4, 5.79M });
sampLabel.Text += ints.DisplayValues();
Let's run it one more time. Click on the Display Values button and your screen will now look like the one shown in Figure 1.1.5:

The program is now working as expected.
So, the big idea of generics at this point is that you can define a generic class. This class can operate equally well on many different data types. For example, you can make a generic class that operates on integers as well as on doubles and decimals.
Now, we will go through it. So, to first step into it, hover your mouse over the T object in the following line in Generics Class.cs:
public GenericsClass(T[] input)
Here, T is essentially like a parameter, so it does have a certain value, which is expressed in the vals = input; line. The first time, T is used for integers. This is how you can step through this code. At the bottom of the screen, the values inside the array are displayed, as shown in Figure 1.1.6:

The t variable, as you can see in Figure 1.1.7, is an integer, and this is how it operates:

Notice also in the screenshot that it's a generics class with an <int> datatype.
The T object in the foreach(T t in vals) line right now represents an integer, and so on for the other data types. So, flexibility of code and reuse of code means that you will write less code. If not for generics, you would have to create individual classes to handle each different data type.
- Learning Cython Programming
- Photoshop智能手機APP UI設(shè)計之道
- Arduino by Example
- React.js Essentials
- Learning SciPy for Numerical and Scientific Computing(Second Edition)
- 現(xiàn)代C++編程實戰(zhàn):132個核心技巧示例(原書第2版)
- 鴻蒙OS應(yīng)用編程實戰(zhàn)
- Vue.js應(yīng)用測試
- 區(qū)塊鏈項目開發(fā)指南
- 快樂編程:青少年思維訓(xùn)練
- C/C++代碼調(diào)試的藝術(shù)
- Mastering Python
- ANSYS FLUENT 16.0超級學(xué)習(xí)手冊
- Visual FoxPro程序設(shè)計實驗教程
- Cocos2D Game Development Essentials