c#泛型中的约束 [英] constraints in c# generic

查看:70
本文介绍了c#泛型中的约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在泛型中使用约束以及我们使用它的原因?请帮我一些例子!!!!!

解决方案

这几乎不能快速回答!



谷歌会给你带来很多结果...



为初学者尝试这个http://www.dotnetperls.com/generic [ ^ ]

然后继续你的研究

http://msdn.microsoft.com/en-us/library/ms379564(v = vs.80).aspx [ ^ ]


如何?很简单,我们在类定义中添加 where 子句:

  public   class  myConstrainedClass< T> 其中 T:IEnumerable 
{
}

这个例子意味着只有当泛型实现IEnumerable时才能实例化该类(即,它可用于 foreach 循环)。

您可以应用其他约束:http://msdn.microsoft.com/en-us/library/vstudio/d5x73970.aspx [ ^ ]



为什么?确保通用代码有效。

如果它需要使用特定的类(或接口),那么它可以访问该类(或接口)的成员 - 如果不这样做那么你只能使用对象类(CloneObject,Equals,GetHashCode,GetType和ToString)中包含的泛型类成员,因为编译器不知道其他成员可以使用什么存在。


How to use constraints in generic and why we use it ? please help me with some examples!!!!!

解决方案

This is hardly something that can be answered "quickly"!

Google will get you many results ...

Try this one for starters http://www.dotnetperls.com/generic[^]
then continue your research here
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx[^]


How? Simple, we add a where clause to the class definition:

public class myConstrainedClass<T>  where T :IEnumerable
    {
    }

This example means that the class can only be instantiated when the generic implements IEnumerable (i.e., it can be used in a foreach loop).
There are other constraints you can apply: http://msdn.microsoft.com/en-us/library/vstudio/d5x73970.aspx[^]

Why? To make sure that the generic code works.
If it expects a specific class (or interface) to be used, then it can access the members of that class (or interface) - if you don't then you can only use generic class members that are included with the object class (CloneObject, Equals, GetHashCode, GetType, and ToString) as the compiler does not know what other members could exist.


这篇关于c#泛型中的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆