C#基础篇1

1.

[html]  view plain copy print ?
  1. using System;  
  2. class A  
  3. {  
  4.     public A()  
  5.     {  
  6.        PrintFields();  
  7.     }  
  8.     public virtual void PrintFields(){}  
  9. }  
  10. class B:A  
  11. {  
  12.     int x=1;  
  13.     int y;  
  14.     public B()  
  15.     {  
  16.        y=-1;  
  17.     }  
  18.     public override void PrintFields()  
  19.     {  
  20.        Console.WriteLine("x={0},y={1}",x,y);  
  21.     }  
  22. }  

 

当使用new B()创建B的实例时,产生什么输出?

 

答:X=1,Y=0

当使用New创建B的实例时,因为B继承了A类,A的构造函数首先会被运行,但应当注意的是,虽然运行的是A的构造函数,但在A的构造函数中调用的函数首先是在B类中查找,因为PrintFields已被重写,所以最终运行B类中的PrintFields函数。

 

 2.什么是单例模式,写个运用单例模式的类

    Singleton模式包含的角色只有一个,就是Singleton。Singleton拥有一个私有构造函数,确保用户无法通过new直接

    实例它

 

[html]  view plain copy print ?
  1. // Singleton pattern -- Structural example    
  2. using System;  
  3.   
  4. // "Singleton"  
  5. class Singleton  
  6. {  
  7.   // Fields  
  8.   private static Singleton instance;  
  9.   
  10.  // Constructor  
  11.  protected Singleton() {}  
  12.   
  13.  // Methods  
  14.  public static Singleton Instance()  
  15. {  
  16.   // Uses "Lazy initialization"  
  17.    if( instance == null )  
  18.      instance = new Singleton();  
  19.   
  20.   return instance;  
  21.   }  
  22. }  
  23.   
  24. /** <summary>  
  25. /// Client test  
  26. /// </summary>  
  27. public class Client  
  28. {  
  29.  public static void Main()  
  30. {  
  31.    // Constructor is protected -- cannot use new  
  32.    Singleton s1 = Singleton.Instance();  
  33.    Singleton s2 = Singleton.Instance();  
  34.   
  35.    if( s1 == s2 )  
  36.      Console.WriteLine( "The same instance" );  
  37.  }  
  38. }  

时间换算


//定义获取时间函数,返回值为字符串
pubilc string getTime(int t)

//计算小时,用毫秒总数除以(1000*60*24),后去掉小数点
int hour = t/(1000*60*24); 
//计算分钟,用毫秒总数减去小时乘以(1000*60*24)后,除以(1000*60),再去掉小数点 
int min = (t - hour*(1000*60*24))/(1000*60); 
//同上 int sec = (t - hour*(1000*60*24) - min*(1000*60))/1000; 
int msec = t - hour*(1000*60*24) - min*(1000*60) - sec*1000; 
//拼接字符串 
strint timeString = hour.toString() +":"+ min.toString() +":"+ sec.toString() +":"+ msec.toString(); 
return timeString;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值