泛型约束简介
C#泛型要求对"所有泛型类型或泛型方法的类型参数"的任何假定,都要基于"显式的约束",以维护C#所要求的类型安全.
"显式约束"有where字句表达,可以指定"基类约束","接口约束","构造器约束","值类型/引用类型约束"共四中约束.
"显示约束"并非必须,如果没有指定"显式约束",泛型类型参数将只能访问System.Object类型中的公有方法.
基类约束
class A
{
public void F1(){}
}
class B
{
public void F2(){}
}
class C(S,T)
where S:A // S继承自A
where T:B // T继承自B
{
// 可以在类型为S的变量上调用F1
// 可以在类型为T的变量上调用F2
}
接口约束
interface IPrintable{void Print();}
interface IComparable<T>{int CompareTo(T v);}
interface IKeyProvider<T>{T HetKey();}
class Dictionary<K,V>
where K:IComparable<K>
where V:IPrintable,IKeyProvider<K>
{
// 可以在类型为K的变量上调用CompareTo
// 可以在类型为V的变量上调用Print和HetKey
}
构造器约束
class A
{
public A(){}
}
class B
{
public B(int i)()
}
class C<T>
where T:new()
{
// 可以在其中使用T t = new T();
}
C<A> c = new C<A>(); // 可以,A有无参数构造器
C<B> c = new C<B>(); // 错误,B没有无参数构造器
值类型/引用类型约束
public struct A{...}
public class B{...}
class C<T>
where T : struct
{
// T在这里面是一个值类型
}
C<A> c = new C<A>(); // 可以,A是一个值类型
C<B> c = new C<B>(); // 错误,B是一个引用类型
using System;
using System.Collections.Generic;
using System.Text;
namespace fanxing
{
interface interface1
{
int add(int a, int b);
}
class class1
{
public int minus(int a, int b)
{
return a - b;
}
}
class class2:class1,interface1
{
public int add(int a, int b)
{
return a + b;
}
}
class stack1<T> where T : class1, interface1
{
public string plus(T t)
{
return t.add(8,4).ToString()+"---"+t.minus(8,4).ToString();
}
}
class Program
{
static void Main(string[] args)
{
class2 intef1 = new class2();
stack1<class2> st = new stack1<class2>();
Console.Write(st.plus(intef1));
Console.Read();
}
}
}
class stack1<T> where T : class1, interface1
{
public string plus(T t)
{
return t.add(8,4).ToString()+"---"+t.minus(8,4).ToString();
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace fanxing
{
interface interface1
{
int add(int a, int b);
}
class class1
{
public int minus(int a, int b)
{
return a - b;
}
}
class class2:class1,interface1
{
public int add(int a, int b)
{
return a + b;
}
}
/*class stack1<T> where T :new()
{
public T mode()
{
T t = new T();
return t;
}
}*/
class stack1<T> where T : class1,new()
{
public int mode()
{
T t = new T();
return t.minus(8, 4);
}
}
class Program
{
static void Main(string[] args)
{
class2 intef1 = new class2();
stack1<class2> st = new stack1<class2>();
Console.Write(st.mode());
Console.Read();
}
}
}
发表于 @ 2008年04月03日 15:27:00 | 评论( loading... ) | 举报| 收藏