无法理解什么是“Where T:”在 C# 中
public class TwitterResponse<T>
where T : Core.ITwitterObject
{
// all properties and methods here
}
有人可以简单地向我解释一下这是什么吗?这里的“where T:Core.ITwitterObject”部分是什么?在 Twitterizer 源代码中看到了这一点。有什么例子可以更好地理解这一点吗?
public class TwitterResponse<T>
where T : Core.ITwitterObject
{
// all properties and methods here
}
Can someone explain me what is this in simple terms ? what is "where T :Core.ITwitterObject " part here ? Have seen this in Twitterizer source code. Any examples to better understand this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这意味着
T
必须实现接口Core.ITwitterObject
。如果将未实现此接口的类型
T
传递给泛型,则会发生编译时错误。此条件允许编译器在
T
实例上调用在Core.ITwitterObject
中声明的函数。有关详细信息,请参阅文档 。
示例:
这比常规方法有一个优势
,因为像
First
这样的方法会更加类型安全,您不需要从IFoo
向下转换为SomeRandomFooImpl< /代码>。
This means that
T
must implement interfaceCore.ITwitterObject
.If you pass to the generic a type
T
not implementing this interface, a compile-time error occurs.This condition allows the compiler to call the functions which are declared in
Core.ITwitterObject
on instances ofT
.Look at the documentation for more information.
Example:
This has an advantage over the customary
because the methods like
First
would be more type-safe, you won't need to downcast fromIFoo
toSomeRandomFooImpl
.它是对泛型类型 T 的约束。这意味着 T 只能是
Core.ITwitterObject
类型it is a constrain on the generic type T. It means T can only be a
Core.ITwitterObject
type这是泛型的约束,因此该约束表示它必须实现 Core.ITwitterObject。
http://msdn.microsoft.com/en-us /库/d5x73970%28VS.80%29.aspx
It's a constraint for generics, so the constraint says it must implement Core.ITwitterObject.
http://msdn.microsoft.com/en-us/library/d5x73970%28VS.80%29.aspx
where
关键字指定泛型类定义中的T
可以表示什么类型。在这种情况下,这意味着只能表示 ITwitterObject(大概是一个接口),即您只能使用实现 ITwitterObject 接口的对象。这里有一个非常清楚的解释。关键摘录:
The
where
keyword specifies what type(s) can be represented by theT
in the generic class definition. In this case it means that only ITwitterObject (presumably an interface) can be represented, i.e. that you can only use objects that implement the ITwitterObject interface.There's a pretty clear explanation here. Key excerpt: