未改造之泛型类:
using System;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApp2
{
class Store
{
private int[] arr = new int[100];
public void Put(int v, int index) {
arr[index] = v;
}
}
internal class Program
{
static void Main(string[] args)
{
}
}
}
泛型之写法:
using System;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApp2
{
class Store<MyT>
{
private MyT[] arr = new MyT[100];
public void Put(MyT v, int index) {
arr[index] = v;
}
}
internal class Program
{
static void Main(string[] args)
{
Store<int> stor = new Store<int>();
}
}
}
泛型方法之写法:
using System;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApp2
{
class Store<MyT>
{
private MyT[] arr = new MyT[100];
public void Put(MyT v, int index) {
arr[index] = v;
}
}
internal class Program
{
static void Main(string[] args)
{
Store<int> stor = new Store<int>();
//泛型的使用。
int m = 10, n = 20;
Swap<int>(ref m, ref n);
}
//泛型方法的写法
static void Swap<T>(ref T a, ref T b) {
T tmp = a;
a = b;
b = tmp;
}
}
}
泛型方法之写法 return 之报错:
using System;
using System.Collections;
using System.Diagnostics;
namespace ConsoleApp2
{
class Store<MyT>
{
private MyT[] arr = new MyT[100];
public void Put(MyT v, int index) {
arr[index] = v;
}
}
internal class Program
{
static void Main(string[] args)
{
Store<int> stor = new Store<int>();
//泛型的使用。
int m = 10, n = 20;
Swap<int>(ref m, ref n);
}
static void Swap<T>(ref T a, ref T b) {
T tmp = a;
a = b;
b = tmp;
}
//求2个参数的相加
static public T Ab<T>(T a, T b) {
dynamic da = a;
dynamic db = b;
return da + db;
}
}
}