public class TwitterResponse<T>
where T : Core.ITwitterObject
{
// all properties and methods here
}
Run Code Online (Sandbox Code Playgroud)
有人可以用简单的术语解释这是什么吗?什么是"哪里T:Core.ITwitterObject"在这里?在Twitterizer源代码中看到了这一点.有什么例子能更好地理解这个吗
这意味着T必须实现接口Core.ITwitterObject.
如果传递给T未实现此接口的泛型类型,则会发生编译时错误.
这个条件允许编译器调用Core.ITwitterObject在实例上声明的函数T.
查看文档以获取更多信息.
例:
interface IFoo { void Perform(); }
class FooList<T> where T : IFoo
{
List<T> foos;
...
void PerformForAll()
{
foreach (T foo in foos)
foo.Perform(); // this line compiles because the compiler knows
// that T implements IFoo
}
}
Run Code Online (Sandbox Code Playgroud)
这具有优于惯例的优点
interface IFoo { void Perform(); }
class FooList
{
List<IFoo> foos;
...
void PerformForAll()
{
foreach (IFoo foo in foos)
foo.Perform();
}
// added example method
IFoo First { get { return foos[0]; } }
}
Run Code Online (Sandbox Code Playgroud)
因为方法,如First将更加类型安全,您将不再需要从向下转型IFoo到SomeRandomFooImpl.