泛型约束(值类型和引用类型)

来源:互联网 发布:ubuntu翻墙上google 编辑:程序博客网 时间:2024/06/03 20:35
public class People{    public int Id { get; set; }    public string Name { get; set; }    public void SayHi()    {        Console.WriteLine("morning!");    }} public class GenericConstrint{   public static void Show<T>(T tValue) where T : People   {       tValue.SayHi();   }   /// <summary>   /// 值类型约束   /// </summary>   /// <typeparam name="T"></typeparam>   /// <param name="t"></param>   public static T GetValue<T>(T t) where T : struct   {            return default(T);   }   /// <summary>   /// 引用类型约束   /// </summary>   /// <typeparam name="T"></typeparam>   /// <param name="t"></param>   public static T GetRef<T>(T t) where T : class   {       return null;//引用类型,所以可以返回null   }}

使用代码:

GenericConstrint.GetValue<decimal>(100m);GenericConstrint.GetValue<int>(100);GenericConstrint.GetValue<float>(100f);GenericConstrint.GetRef<string>("1234");GenericConstrint.GetRef<People>(p);
原创粉丝点击