C#泛型约束

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

namespace 泛型约束
{ 
    public class AGenericClass<T> where T : IComparable<T> { }//接口约束

    //类型约束
    public class UsingEnum<T> where T : System.Enum //枚举型
    {
      public  void wr()
        {
            Console.WriteLine("被约束为枚举类型种的方法");
        }
    }//约束T必须是枚举类型

    public class UsingDelegate<T> where T : System.Delegate { }//约束类型必须是委托类型

    public class Multicaster<T> where T : System.MulticastDelegate { }//多播委托型

    class MyClass<T, U>//约束2个参数
    where T : class
    where U : struct
    { }

    public abstract class B
    {
        public void M<T>(T? item) where T : struct { }//T约束为结构体,可以是null
       // public abstract void M<T>(T? item);

    }
    public class MyGenericClass<T> where T : IComparable<T>, new()// new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数构造函数
    {
        // The following line is not possible without new() constraint:
        //没有new()约束,以下行是不可能的:
        T item = new T();
    }

    delegate T MyDelegate<T>() where T : new();//泛型委托约束同上

    //泛型方法种也是可以约束的
    class a
    {
        public interface IMyInterface { }
        public void MyMethod<T>(T t) where T : IMyInterface { } //意思T必须是接口
    }

    //以下是例子

    public class SingletonTemplate<T> where T : class, new()//单例模式,越是T必须为类,且构造函数必须有无参的
    {
        //
        // 摘要:
        //     实例引用
        private static T m_instance;
        //
        // 摘要:
        //     线程互斥对像
        private static readonly object syslock = new object();
        // 摘要:
        //     获取实例
        public static T GetInstance()
        {
            if (m_instance == null)
            {
                lock (syslock)
                {
                    if (m_instance == null)
                    {
                        m_instance = new T();
                    }
                }
            }

            return m_instance;
        }


    }
    public class SigleMgr : SingletonTemplate<SigleMgr>//继承单件泛型类的目的是 SigleMgr 全局就一个对象
    {
        public void M()
        {
            Console.WriteLine("我是管理类种的一个方法");
        }
        
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            AGenericClass<int> aGeneric = new AGenericClass<int>();
           
            //这个是错误的
            //UsingEnum<int> usingEnum = new UsingEnum<int>();
            //这个是正确的,T被约束为必须是枚举
            UsingEnum<TestEnum> usingEnum = new UsingEnum<TestEnum>();
            usingEnum.wr();

            SigleMgr.GetInstance().M();
            Console.ReadKey();
        }
    }
    enum TestEnum
    {
    A,B,C,D

    }
}

 

posted @ 2023-02-03 14:56  灰色淡季  阅读(93)  评论(0)    收藏  举报