namespace eTType
{
interface ISpeak
{
void Speak();
}
class Person : ISpeak
{
private string name;
public Person()
{
}
public Person(string name)
{
this.name = name;
}
public void Speak()
{
Console.WriteLine("人类说话...");
}
}
class Programmer : Person
{
}
class Bird : ISpeak
{
public void Speak()
{
Console.WriteLine("鸟说话,渣渣渣..");
}
}
internal class Program
{
enum GameType
{
RPG,RTS
}
public static void Main(string[] args)
{
int a = 10;
int b = 20;
//使用泛型方法
Swap<int>(ref a,ref b);
char c = 'F';
char d = 'M';
Swap<char>(ref c,ref d);
string str01 = "111";
string str02 = "222";
Swap(ref str01,ref str02);
Test(1,0.4f,'0',"sss",2,2.5f,new Program());
GameType type01 = GameType.RPG;
GameType type02 = GameType.RTS;
SwapValueType(ref a,ref b);
SwapValueType(ref type01,ref type02);
// SwapValueType(ref str01,ref str02);
SwapReference(str01,str02);
// SwapReference(a,b);
Person xiaoming = new Person("小明");
a = new Int32();
GameType gt = GameType.RPG;
Console.WriteLine("枚举传参...");
Demo(gt);
Programmer mm = new Programmer();
InhertDemo(xiaoming);
InhertDemo(mm);
ISpeak speak = null;
Bird bird = new Bird();
InterfaceDemo(speak);
InterfaceDemo(bird);
// T : Bird U : ISpeak
GenericDemo(bird,speak);
// T : Programmer U : Person
GenericDemo(mm,xiaoming);
// T : Person U : Person
GenericDemo(xiaoming,xiaoming);
}
//【泛型方法】——在方法中出现泛型
//通过一个字母或一个单词表示一个泛泛的类型
//在方法的后面用尖括号括起来
//此时该泛型就用在参数、返回值、方法体中进行使用
static void Swap<T>(ref T varable01, ref T varable02)
{
//中间变量
T temp = varable01;
varable01 = varable02;
varable02 = temp;
}
//限制泛型T必须是一个值类型,不能是其他类型
static void SwapValueType<T>(ref T v01, ref T v02) where T : struct
{
T temp = v01;
v01 = v02;
v02 = temp;
}
//两个引用类型交换
//引用类型泛型的约束
static void SwapReference<T>(T ref01,T ref02) where T : class
{
//0x01
T temp = ref01;
//0x02
ref01 = ref02;
//0x01
ref02 = temp;
}
static void Demo<T>(T parameter) where T : new()
{
parameter = new T();
Console.WriteLine(parameter);
}
//泛型A,必须是Person类型或Person类型的子类
static void InhertDemo<A>(A para) where A : Person
{
}
//
static void InterfaceDemo<T>(T para) where T : ISpeak
{
}
//泛型T必须是U类型,或是U类型的子类or实现者
static void GenericDemo<T, U>(T p1, U p2) where T : U
{
}
static void Demo<TKey, TValue>()
{
}
static void Test<A, B, C, D, FF, ABC, INT>(
A a,B b,C c,D d,FF ff,ABC abc,INT i)
{
}
}
}
c#-- 泛型
最新推荐文章于 2023-08-21 09:56:57 发布