初识c#---泛型

/// 泛型
 
namespace _0817_ClassCode
{
 
    /// 泛型需要注意的地方:
    /// 1.T只是占位符,没有实际的意义,所以不能运用四则运算(+-*/),关系运算符
    /// 2.T仅仅可以有赋值操作
    /// 3.T可以限定的类型(常用的),值类型,引用类型,接口
    /// 4.where T :struct 限定T为值类型
    /// 5.where T:class 限定T为引用类型
    /// 6.where T: 接口 限定实现接口
 
    class Program
    {
        //T:struct 限定T的类型为值类型
        public void Swap<T>(ref T a,ref T b) where T :struct
        {
            T c = default(T);
            c = a;
            a = b;
            b = c;
        }
        //限定多个参数
        public void Show<U,O>(U a,O b)where U:struct where O:class
        {     
            Console.WriteLine(a);
            Console.WriteLine(b);
        }

        //演示接口限定
        //如果一个泛型T有多个限定,那么class和struct要放在最前面
        public T Comp<T>(T a,T b)where T:class,IComparable
        {
            if (a.CompareTo(b) < 0)
            {
                return b;
            }
            else
            {
                return a;
            }
            
        }
         
        static void Main(string[] args)
        {
            
            int a = 10;
            int b = 20;
            //当T限定为引用类型的时候,调用下列代码会出现编译错误
            new Program().Swap<int>(ref a, ref b);
            Console.WriteLine("a的值{0} b的值{1}",a,b);

            //交换string类型变量
             string s1 = "1";
             string s2 = "2123465";
            //当T限定为值类型的时候,调用下面代码会出现编译错误
            // new Program().Swap<string>(ref s1, ref s2);
            // Console.WriteLine("s1:{0},s2:{1}",s1,s2);

            //比较两个字符串,返回比较大的
           string str= new Program().Comp<string>(s1, s2);
            Console.WriteLine(str);
            Console.ReadKey();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值