标签:test 装箱 swap sum int new bsp json ati
? 泛型的产生其中一个原因就是为了解决原来集合类中元素的装箱和拆箱问题:
一、泛型类:
/// <summary> /// 返回前台的消息 /// </summary> /// <typeparam name="T"></typeparam> public class YZT_Message<T> { private int m_Request_Type = 1; // 返回前台的成功错误类型:1:成功(默认) 0:错误 public int Request_Type { get { return m_Request_Type; } set { m_Request_Type = value; } } private string m_Request_Message = "当前错误"; //返回前台的信息 Request_Type == 0 时,才会取当前错误数据 public string Request_Message { get { return m_Request_Message; } set { m_Request_Message = value; } } // 回返前台的信息,可能是JSON对象 public T Request_Object { get; set; } // 回返前台的信息,可能是JSON对象集合 public IList<T> Request_List { get; set; } }
调用的时候:假如T是string类型:
YZT_Message<string> pMessage = new YZT_Message<string>();
try{
pMessage.Request_Object = "OK";
pMessage.Request_Type = 1;
}
catch (Exception err){
pMessage.Request_Type = 0;
pMessage.Request_Message = err.Message;
}
二、泛型方法:
public class Demo { //这是一个泛型方法,可以在普通类中 public static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } //调用泛型方法: public static void TestSwap() { int a = 1; int b = 2; Swap<int>(ref a, ref b);//也可以省略类型参数,编译器将推断出该参数。Swap(ref a, ref b); System.Console.WriteLine(a + " " + b); } }
三、泛型接口
public class Demo { public interface IFace<T> { T SayHi(); void SayHello(T msg); } }
实现泛型接口:
方式一:普通类实现泛型接口:
public class InterFaceDemo2 : WebApplication1.InterFaceDemo.IFace<string> { public string SayHi() { throw new NotImplementedException(); } public void SayHello(string msg) { throw new NotImplementedException(); } }
方式二:泛型类,实现泛型接口,这样更灵活
public class InterFaceDemo<T>:WebApplication1.InterFaceDemo.IFace<T> { public T SayHi() { throw new NotImplementedException(); } public void SayHello(T msg) { throw new NotImplementedException(); } }
标签:test 装箱 swap sum int new bsp json ati
原文地址:https://www.cnblogs.com/qicao/p/9126060.html