首页 > 代码库 > 泛型约束

泛型约束

一,引用类型的约束

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassTdemo
{
    class Program
    {
        //在应用 where T : class 约束时,避免对类型参数使用 == 和 != 运算符,因为这些运算符仅测试引用同一性而不测试值相等性
        public static void Test<T>(T s, T t) where T : class
        {
            System.Console.WriteLine(s == t);    //当判断值时,会输出false,where T : class约束对传入类型存在约束,但使用运算符判断不了值相等新
            Console.WriteLine(s.GetType());
            Console.WriteLine(t.GetType());
        }
        static void Main(string[] args)
        {
            string s1 = "tar";
            System.Text.StringBuilder sb = new System.Text.StringBuilder("tar");
            string s2 = sb.ToString();
            Test<string>(s1, s2);
        }
    }
}

二,泛型值类型约束

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StructTdemo
{
    class Program
    {
        public static void Test<T>(T s) where T : struct
        {
            System.Console.WriteLine(s.ToString());    
            Console.WriteLine(s.GetType());
        }
        static void Main(string[] args)
        {
            st s = new st();
            s.Name = "1";

            st2 s2 = new st2();
            s2.Name2 = "2";

            Test<st>(s);
        }
    }
    struct st
    {
        public string Name { get; set; }
    }
    struct st2
    {
        public string Name2 { get; set; }
    }
}

 三,无构造函数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NewTdemo
{
    class Program
    {
        public class NewTest<T> where T : new()
        {
            T t;
            public NewTest()
            {
                t = new T();
            }
        }
        public class Test
        {
            //public Test(string a) {
            //    Console.WriteLine(a);  //出现构造函数会报错
            //}
        }
        static void Main(string[] args)
        {
            NewTest<Test> N = new NewTest<Test>();
        }
    }
}

 

泛型约束