Recently inadvertently saw: Http://msdn.microsoft.com/zh-cn/library/bb384067.aspx. But, people stupid ah, Wood has to understand what the meaning of the end, wood approach to write a try it, right as a note
Examples are as follows:
Interface:
Using system;using system.collections.generic;using system.linq;using system.text;namespace WhereTest{// < summary> ///fruit interface///</summary> public interface ifruit { //fruit name string fruitname { get; Set; } String GetName (); The/* interface can contain only declarations of methods, properties, indexers, and events. * It is not allowed to declare modifiers on members, even PUBILC, because interface members are always public and cannot be declared as virtual and static. * If modifiers are required, it is best to have the implementation class declared. */ }}
Interface implementation:
Using system;using system.collections.generic;using system.linq;using system.text;namespace WhereTest{// < summary> ///Pear class///</summary> public class Peach:ifruit {//No parameters, common constructors Peach () { } private string fruitname; String Ifruit.fruitname { get { return this. ToString ();; } Set { fruitname = value; } } String Ifruit.getname () { return string. IsNullOrEmpty (fruitname)? "Wood has a name to find": Fruitname;}}
Create a class with a generic constraint:
Using system;using system.collections.generic;using system.linq;using system.text;namespace WhereTest{// < summary>/// classes with generic constraints///</summary>// <typeparam name= "T" ></typeparam> public class fruitmarket<t> where T:ifruit, new ()//new () means that this T must have the public constructor { T item = new T ( ); public void Fruitsayhello () { item. Fruitname = "I am a pear"; Console.WriteLine ("Hello:" + string.) Format ("fruit:{0}", item. GetName ())); Console.readkey (); } /* When defining a generic class, you can impose restrictions on the type types that client code can use for type parameters when instantiating a class. * If the client code attempts to instantiate a class using a type not allowed by a constraint, a compile-time error occurs. */ }}
Because of the generic constraints of the WHERE clause, when you create an Fruitmarket object, the type of T can only be a class that inherits from the Ifruit interface.
Using system;using system.collections.generic;using system.linq;using system.text;namespace WhereTest{ class Program { static void Main (string[] args) { //instantiation can only invoke the corresponding method in the static method, otherwise the peach variable is not found at all fruitmarket<peach> Peach = new fruitmarket<peach> (); Peach. Fruitsayhello ();}}}
Operation Result:
C # where generic constraints and new