您的位置:首页 > 编程语言 > C#

C#的泛型约束-

2016-05-10 17:07 429 查看
`class b

{

}

class c

{

public c(string s)

{

}
public void hello<T>(T t) where T: new()
{
}


}

class a where T:class { public T x; }public class FanxingClient : MonoBehaviour {

void Start () {
a<c> abc = new a<c>();
abc.x.hello<b>(new b());

a<c> abc2 = new a<c>();
abc2.x = new c("");
}`


记一下笔记今天学习了下 C#中的泛型约束 对类的约束和对方法的约束

类的约束:

class a where T:class

{

public T x;

}


限制泛型类的T类型只能为引用类型,还可以用struct, 限制为值类型也可以直接用int,float等关键字.

方法的约束:

public void hello<T>(T t) where T: Struct
{
}


和类的约束类似,只是还可以进行参数的约束

public void hello<T>(T t) where T: new()
{
}


限制只能用无参的构造方法

注:自己的一些理解,不对的地方,欢迎指出来~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: