1.单例模式
/// <summary> /// 单例模式 /// </summary> /// <typeparam name="T"></typeparam> public class Singleton<T> where T:new () { public static T Instance { get { return SingletonCreator.instance; } } public class SingletonCreator { internal readonly static T instance=new T(); } }
2.冒泡排序
/// <summary> /// 冒泡排序 /// </summary> public static void MaoPao() { int[] arry = { 30, 6, 5, 15, 13, 18, 10, 36, 25 }; for (int i = 0; i < arry.Length - 1; i++) { for (int j = i + 1; j < arry.Length; j++) { int temp; if (arry[i] > arry[j]) { temp = arry[i]; arry[i] = arry[j]; arry[j] = temp; } } } foreach (var item in arry) { Console.Write("-" + item + "-"); } } }
3.递归算5的阶乘,我只算出了最终结果,可以深入点的话,有兴趣的可以写个5!=5*4*3*2*1,4!=4*3*2*1这样输出,稍加改动应该简单
/// <summary> /// 递归算法 /// </summary> public static int Recursion(int m) { if (m <= 1) return 1; else { return m * Recursion(m - 1); } }
4.不使用第三变量交换两个变量值,(写牛逼点,那就用位运算吧,第一种我注释掉了)
public static void jiaohuan() { //int i = 500; //int j = int.MaxValue - 10; ////int i = 10; ////int j = 20; //Console.WriteLine("i={0},j={1}", i, j); //i = i + j;//i=30 //j = i - j;//j=10; //i = i - j;//i=20; int m = 9; int n = 5; Console.WriteLine("初始值"); Console.WriteLine(m); Console.WriteLine(n); Console.WriteLine("中间变化"); m = m ^ n; Console.WriteLine(m); n = n ^ m; Console.WriteLine(n); m = m ^ n; Console.WriteLine("交换过的值"); Console.WriteLine(m); Console.WriteLine(n); }
5.这种继承基类的面试题很普遍吧,拿来解析一下,有待研究,有什么不足之处,可以交流一下类之间关系
#region 基类继承,重写问题 public class Fruit { public Fruit() { FruitName = "Fruit"; WriteFruitName(); } public virtual void WriteFruitName() { Console.WriteLine("Fruit‘s WriteFruitName(),The Name Is " + FruitName); } protected string FruitName { get; set; } } public class Banana : Fruit { public Banana() { FruitName = "Banana"; // WriteFruitName();//在这调用和不调用两种截然不同的结果 } public override void WriteFruitName() { Console.WriteLine("Banana‘s WriteFruitName(),The Name Is " + FruitName); } } #endregion
调用输出结果,注意看注释哦,写的很经典,很遗憾,那是我摘至别人之手,看不懂的,可以调试一下,看看运行过程,怎么调用的,也许你就恍然大悟了,
//执行结果是:Banana‘s WriteFruitName(),The Name Is Fruit。 //原因就是调用虚方法时,发现子类覆载了该方法,所以调用Banana类的WriteFruitName, //但此时Banana类的构造器还没被执行,也就是说FruitName属性在Banana类中还没被赋值呢,而基类的构造器给它赋值为Fruit。 Banana b = new Banana(); // 执行结果是:Banana‘s WriteFruitName(),The Name Is Banana。 b.WriteFruitName();
由于时间关系,要下班了,工厂模式,都没写,以后再写吧,有什么不对的地方可以留言,大家一起交流一下
时间: 2024-10-15 21:38:25