什么"其中"意味着一个C#类的声明? [英] What does "where" mean in a C# class declaration?

查看:129
本文介绍了什么"其中"意味着一个C#类的声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图谷歌这一点,但我能找到的是普通类的声明文件。

I tried to google this, but all I could find was documents on ordinary class declarations.

public class DataContextWrapper<T> : IDataContextWrapper where T : DataContext, new()
{

}

我看到类实现IDataContextWrapper,从DataContext的继承和T型的变化取决于它是如何被实例化。

I see that the class implements IDataContextWrapper, inherits from DataContext and varies with type T depending on how it is instantiated.

我不知道什么是其中T ,新的()可能意味着。

I don't know what "where T" or the ", new()" might mean.

推荐答案

这是一个泛型约束和限制什么类型都可以传递到泛型参数。

It's a generic constraint and restricts what types can be passed into the generic parameter.

在你的情况下,它要求 T 是张玉峰,或从的DataContext 派生而来,有一个默认的(argumentless)构造函数(即新()约束)。

In your case it requires that T is indentical to or derived from DataContext and has a default(argumentless) constructor(the new() constraint).

您需要通用的约束,实际上是做一些不平凡了泛型类型。

You need generic constraints to actually do something non trivial with a generic type.

  • 新()的限制,您可以创建一个实例新T()
  • 的DataContext 的限制,您可以调用的DataContext 的实例的方法牛逼
  • The new() constraint allows you to create an instance with new T().
  • The DataContext constraint allows you to call the methods of DataContext on an instance of T

MSDN写道:

其中T:其中,基础类名称&gt;   类型参数必须是或从指定的基类派生。

where T : <base class name> The type argument must be or derive from the specified base class.

其中T:新的()   类型参数必须有一​​个公共的无参数的构造函数。当与其他约束一起使用时,new()约束必须最后指定。

where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

这篇关于什么&QUOT;其中&QUOT;意味着一个C#类的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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