One of the problems with object-oriented programming is the so-called "code expansion" feature. To illustrate all possible data types of method parameters, code expansion occurs when you need to overload a method or reload a set of methods. One solution to code expansion is to make a value present multiple data types, and only provide a definition of this value. This method is called model programming. Model programming provides a data type "placeholder ". It is filled by a specific data type during compilation. This placeholder is represented by an identifier between a pair of angle brackets (<>) and placed between brackets. Let's look at an instance.
static void Swap<T>(ref T val1, ref T val2){ T temp; temp = val1; val1 = val2; val2 = temp;}
Immediately place the Data Type placeholder behind the function name. The identifier placed in the angle brackets can be used whenever the fan data type is required. Just like a temporary variable for exchange, each parameter gets a fan data type. The following is a program to test the code.
class chapter1{ static void Main() { int num1 = 100; int num2 = 200; Console.WriteLine("num1: "+ num1); Console.WriteLine("num2: " + num2); Swap<int>(ref num1, ref num2); Console.WriteLine("num1: " + num1); Console.WriteLine("num2: " + num2); string str1 = "Sam"; string str2 = "Tom"; Console.WriteLine("String 1: " + str1); Console.WriteLine("String 2: " + str2); Swap<string>(ref str1, ref str2); Console.WriteLine("String 1: " + str1); Console.WriteLine("String 2: " + str2); }}
The parameter type has no restrictions on function definitions. You can also create a fan class. The definition of a fan class includes a placeholder for the fan type following the class name. A placeholder type must be provided when a class name is referenced in any definition. The following class definition describes how to create a fan class:
public class Node<T>{ T data; Node<T> link; public Node(T data, Node<T> link) { this.data = data; this.link = link; }}
The usage is as follows:
Node<string> node1 = new Node<string>("Mike", null);Node<string> node2 = new Node<string>("Raymond", node1);
Although this usage of model programming may be very useful, the C # language provides a standby model data structure library.