概述
public class Compare<T>
{
public void Max(T a, T b)
{
Type type = typeof(T);
if (type.Name == "Int32")
{
if (Convert.ToInt32(a) > Convert.ToInt32(b))
Console.WriteLine("最大值:{0}", a);
else
Console.WriteLine("最大值:{0}", b);
}
else if (type.Name == "Double")
{
if (Convert.ToDouble(a) > Convert.ToDouble(b))
Console.WriteLine("最大值:{0}", a);
else
Console.WriteLine("最大值:{0}", b);
}
else if (type.Name == "Single")
{
if (Convert.ToSingle(a) > Convert.ToSingle(b))
Console.WriteLine("最大值:{0}", a);
else
Console.WriteLine("最大值:{0}", b);
}
}
}
class Program
{
static void Main(string[] args)
{
Compare<int> comparei = new Compare<int>();
comparei.Max(5, 6);
Compare<double> compared = new Compare<double>();
compared.Max(5.3d, 6.6d);
Compare<float> comparef = new Compare<float>();
comparef.Max(5.3f,6.6f);
Console.ReadKey();
}
}
public class Compare<T> where T : IComparable,new()
{
//使用泛型实现的比较方法
public T Comparesize(T t1, T t2)
{
if (t1.CompareTo(t2) > 0)
{
return t1;
}
else
{
return t2;
}
}
}
class Program
{
static void Main(string[] args)
{
Compare<int> cin = new Compare<int>();
Console.WriteLine(cin.Comparesize(5, 4));
Compare<double> din = new Compare<double>();
Console.WriteLine(din.Comparesize(5.32d, 4d));
Compare<float> fin = new Compare<float>();
Console.WriteLine(fin.Comparesize(5.63f, 4f));
Console.ReadKey();
}
}
public class Compare<T>
{
public void Max(T a, T b)
{
if (Convert.ToDouble(a) > Convert.ToDouble(b))
Console.WriteLine("最大值:{0}", a);
else
Console.WriteLine("最大值:{0}", b);
}
}
class Program
{
static void Main(string[] args)
{
Compare<int> comparei = new Compare<int>();
comparei.Max(5, 6);
Compare<double> compared = new Compare<double>();
compared.Max(5.3d, 6.6d);
Compare<float> comparef = new Compare<float>();
comparef.Max(5.3f,6.6f);
Console.ReadKey();
}
}
最后
以上就是奋斗短靴为你收集整理的创建一个泛型类比较大小的全部内容,希望文章能够帮你解决创建一个泛型类比较大小所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复