开发者

cant understand what is "Where T:" in C#

 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 ?


This means that T must implement interface Core.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 of T.

Look at the documentation for more information.

Example:

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
    }
}

This has an advantage over the customary

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]; } }
}

because the methods like First would be more type-safe, you won't need to downcast from IFoo to SomeRandomFooImpl.


it is a constrain on the generic type T. It means T can only be a Core.ITwitterObject type


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


The where keyword specifies what type(s) can be represented by the T 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:

When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code attempts to instantiate your class with a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified using the where contextual keyword.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜