zoukankan      html  css  js  c++  java
  • where TEntity : calss 语法来源

    where TEntity : calss 语法来源

    代码:
    public interface IEntitiesProvider
    {
       void Refresh(TEntity entity) where TEntity:class;
    }
    场景:这段代码,简答的多了,可以大致猜出来他是什么意思:定义了一个刷新一个实体的 方法。

              但是 where TEntity:class 真的能知道这个原理的到时 不全。

    发展:今天读别人的代码,到MSDN上看了下才知道出处。及用法的示例:

           

            1.查阅MSDN上where(c#)

               a.定义:where 子句用于指定类型约束,这些约束可以作为泛型声明中定义的类型参数的变量。

               b.示例:

                  1.类型参数 T 就可以实现 IComparable<T> 接口
              public class MyGenericClass<T> where T:IComparable
              {
                   //。。。。。。
              }
    2.where 子句还可以包括基类约束,以指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。
              calss TestClass<T,V>
                    where T:class
                    where V::struct
              {
                   //.........
              }
    3.where 子句还可以包括构造函数约束。可以使用 new 运算符创建类型参数的实例;但类型参数为此必须受构造函数约束 new() 的约束。new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数(或默认)构造函数。
             using System;
             public class MyGenericClass<T> where T:IComparable,new()
             {
                 // The following line is not possible without new() constraint:【下面这一行必须要求有new()出现。】
                 T t=new T();
             }
    new() 约束出现在 where 子句的最后。

    4.对于多个约束参数类型事,要求每个类型 使用一个 where。
           // cs_where_3.cs
           // compile with: /target:library
           using System;
           using System.Collections;

           interface MyInterface { }
             
           class Dictionary  <TKey,TVal>
                   where TKey:IComparable,IEnumrable
                   where TVal:MyInterface
           {
               public void Add(TKey key,TVal val)
               {
                   
               }
           }

     5.还可以将约束附加到泛型方法的类型参数
         public bool MyMehtod<T>(T t) where T:MyI
          {
                 //...........
          }
    6.在delegate的方法中是一样的用法。

         delegate T MyDelegate(T t) where T :new();

  • 相关阅读:
    头信息已输出的报错信息位置定位
    阅读<php程序设计>笔记
    include、ruquire使用相对路径总结
    php中未定义的变量使用技巧
    Oracle官方教材(9i、10G及App 11i)
    Vista的软件兼容性
    轻松找回Vista序列号
    oralce定时执行存储过程任务设置步骤详细
    今天做了内存测试,发现真的是内存问题导致的一连串的问题
    网络邮盘(GMailStore) V3.0.2
  • 原文地址:https://www.cnblogs.com/wahaccp/p/3501583.html
Copyright © 2011-2022 走看看