zoukankan      html  css  js  c++  java
  • C#泛型

    泛型,字面意思就是泛泛而谈的广泛形状,就是偷懒的典型。不过,程序员和工程师们,甚至科学家们发明东西并不是完备考虑的,都是线性思维,先发明出来工具,然后有漏洞再弥补。泛型就是为了省力气发明的。副作用我不知道,但是以后肯定有的。

     

    K用string填充 ,就是string类型。

     

    接口泛型

    namespace fanxinjiekou

    {

    class Program

    {

    static void Main(string[] args)

    {

    Something1 v1 = new Something1();

    v1.OutPut(500, 99.88d);

    //Console.WriteLine("Hello World!");

    Something2<uint, ushort> v2 = new Something2<uint, ushort>();

    v2.OutPut(9009, 17);

    Something2<char, string> v3 = new Something2<char, string>();

    v3.OutPut('c', "cat");

    Read();

    }

    }

     

     

    public interface ITest<P, Q>

    {

    void OutPut(P x, Q y);

    }

    public class Something1 : ITest<int,double>

    {

    public void OutPut(int x,double y)

    {

    WriteLine("{0} - {1}", x.GetType(), x);

    WriteLine("{0} - {1} ", y.GetType(), y);

    }

    }

    public class Something2<J,K> : ITest<J,K>

    {

    public void OutPut(J x, K y)

    {

    WriteLine("{0} - {1}", x.GetType(), x);

    WriteLine("{0} - {1} ", y.GetType(), y);

    }

    }

     

    }

     

     

    前面的我预言到了,声明:我是第一次学泛型,但是我开头说的被我说中了,就是幺蛾子的事情肯定有。后来就看到书中有泛型约束来了。

    就是不能太泛,还要约束一下,唉,约束尼玛啊 ,f*k~~~

     

    约束成功,现在string类型是不可以的

     

    泛型方法:

    namespace fanxinfangfa

    {

    class Program

    {

    static void Main(string[] args)

    {

    Sample s = new Sample();

    // char

    s.DoSomething('z');

    // byte

    s.DoSomething((byte)5);

    // double

    s.DoSomething(6.3333d);

    // int

    s.DoSomething(777);

     

    A xa = s.GetSomething<A>();

    B xb = s.GetSomething<B>();

     

    Console.Read();

    //Console.WriteLine("Hello World!");

    }

    }

    class Sample

    {

    public void DoSomething<T>(T p) where T : struct

    {

    WriteLine("{0}-{1}", p.GetType().Name, p);

     

    }

    public T GetSomething<T>() where T:class,new()

    {

    return new T();

    }

    }

     

    public class A { }

    public class B { }

    }

     

     

     

  • 相关阅读:
    Net使用RdKafka引发异常RdKafka.Internal.LibRdKafka 的类型初始值设定项引发异常
    mysql数据与Hadoop之间导入导出之Sqoop实例
    如何将mysql数据导入Hadoop之Sqoop安装
    常见的几种Flume日志收集场景实战
    Restful服务应不应该在URI中加入版本号
    sudo
    shell实现SSH自动登陆
    使用465端口加密发邮件
    linux下c++如何输入不回显
    tmp
  • 原文地址:https://www.cnblogs.com/ifconfig/p/13163853.html
Copyright © 2011-2022 走看看