1  /  1  页   1 跳转 查看:793

C#经典面试题及答案

C#经典面试题及答案

将比较常见的C#面试题分布出来供有需求的朋友参考,本文章会不断更新。如果有好的面试题不妨给我留言,我来完善。
最好是有答案的。

  1:委托和事件
   
//事件类
    public class EventClass
    {
        public void display(object sender, System.EventArgs e)
        {
            Console.WriteLine("This is the Event Class");
            Console.ReadLine();
        }
    }
    //调用类
    class InvokeClass
    {
        //声明代理对象,注意参数
        public delegate void delegateobj(object sender, System.EventArgs e);
        //声明事件对象
        private event delegateobj obj;
        //声明要调用的事件类对象
        private EventClass ec;

        public InvokeClass()
        {
            ec = new EventClass();
            //添加事件对象到事件队列中,参数为要调用的事件
            this.obj += new delegateobj(ec.display);
        }
        //调用delegate对象触发事件
        protected void OnObj(System.EventArgs e)
        {
            if (this.obj != null)
            {
                obj(this, e);
            }
        }
        public void RaiseEvent()
        {
            EventArgs e = new EventArgs();
            OnObj(e);
        }
        static void Main(string[] args)
        {
            InvokeClass ic = new InvokeClass();
            Console.WriteLine("Please input a string");
            string input = Console.ReadLine();
            if (input.Equals(""))
            {
                Console.WriteLine("Sorry,you don't input anything");
            }
            else
            {
                //触发事件
                ic.RaiseEvent();
            }
        }
    }
     
      2:遍历页面中所有的TextBox,交将值设置成"a"
   
for (int j = 0; j < this.Controls.Count; j++)
            {
                foreach (object o in Page.Controls[j].Controls)
                {
                 
                    if (o is TextBox)
                    {
                        TextBox txt = (System.Web.UI.WebControls.TextBox)o;
                        txt.Text = "A";
                    }
                 
                }
            }
     
        3  常用排序算法
       
/**//// <summary>
        /// /冒泡排序
        /// </summary>
        private void BubbleSort()
        {
            //冒泡排序
            int[] list = new int[5] { 111, 12, 223, 854, -5655 };//初始化数组
            int i, j, temp;
            for (j = 1; j < list.Length; j++)
            {
                for (i = 0; i < list.Length - j; i++)
                {
                    if (list > list[i + 1])
                    {
                        temp = list;
                        list = list[i + 1];
                        list[i + 1] = temp;
                    }
                }

            }
           

        }
        /**//// <summary>
        /// 选择排序
        /// </summary>
        private void SelectSort()
        {
            //选择排序
            int[] a = new int[5] { 111, 12, 223, 854, -5655 };//初始化数组
            int min, min_k;//定义最小数,和最小数的下标
            for (int i = 0; i < 5; i++)
            {
                min = a;//将当前循环的数设置成最小数
                min_k = i;
                for (int j = i + 1; j < 5; j++)
                {

                    if (a[j] < min)
                    {
                        min = a[j];
                        min_k = j;
                        int tem = a[min_k];
                        a[min_k] = a;
                        a = tem;


                    }


                }


            }

        }
     
      4:结构体(Struct) 和 类(Class)
     

      对于结构和类,初看上去都一样。都可以有自己的字段,属性,方法,还能有构造函数。但是这两者其实有很大的不同,而且各自有各自的应用范围。下面还是谈谈两者的分别吧。

      <1> 结构的特点和性能优势

      结构是值类型,继承自System.ValueType。结构相对于类来说有两个性能上的优势,结构通常分配在栈(Stack)上面,类的实际内容通常分配在堆(Heap)上面,访问栈的速度会比访问堆的速度更快。但是这并不是一个明显的优势。最主要的是栈上面的内容释放是非常快的,通常在函数调用结束以后,栈就自动释放了;但是对于堆来说,必须等待垃圾收集器(Garbage Collector)来收集,往往垃圾收集器的工作都有滞后特性,所以我们不一定当时就能注意到性能的变化,但是这种影响终究会体现出来。

      <2> 结构的弱点

      (1)作为参数传递的时候效率低

        (2)装箱(Boxing)和解箱(Unboxing)效率低

    <3>  何时使用结构,何时使用类?

    在下面的情况下使用类

      1 内容很多的时候,因为结构总是暗地里拷贝了一个临时变量。
      2 需要非常多内存的时候,因为栈的容量有限,而堆通常是足够使用的。
      3 需要在声明字段的时候进行初始化。
      4 需要从基类继承。
      5 需要多态性。接口也可以用来实现多态性,但是因为结构是值类型,尽管它可以从接口继承,但是在多态过程中会进行装箱和解箱的操作。
    在下面的情况下使用结构

      1 希望能够象原始类型(比如int,double之类的)一样使用它。比如我们可以声明一个复数结构,然后像double类型一样地使用它。
      2 需要的内存较少,栈可以完全地容纳它。
      3 想避开垃圾收集器的处理,自己掌握资源的释放。
      4 只需要缺省的值,而不需要在声明字段的时候赋值。
      5 不需要从基类继承,当然,不包括ValueType。
      6 不需要多态行为。

      5:给XML文件中已知的结点添加属性:

        XML文件结构如下:

<?xml version="1.0" encoding="utf-8"?>
<MovieBlacklist>
  <Blacklist id="17050" part="32" name="江湖俏佳人" age="20" />
  <Blacklist id="17310" part="1" name="阴谋" />
  <Blacklist id="17316" part="1" name="WWE摔角080314" />
  <Blacklist id="17190" part="1" name="2012世界末日" />
</MovieBlacklist>
     
      给第一个Blacklist添加属性age

/**//// <summary>
          /// 给已知结点增加一个属性
          /// </summary>
          /// <param name="XmlPathNode"></param>
          /// <param name="Content"></param>
        public void XMLAddAttributes(string XmlPathNode,string sName, string sContent)
          {
              // 创建节点
              XmlNode attrCount = objXmlDoc.CreateNode(XmlNodeType.Attribute, sName , null);
              attrCount.Value = sContent ;
              // 添加节点属性
              objXmlDoc.SelectSingleNode(XmlPathNode).Attributes.SetNamedItem(attrCount);
          }

      6.求以下表达式的值,写出您想到的一种或几种实现方法: 1-2+3-4+……+m
答:
int sum=0;
bool flag=true;
for(int i=1;i<=m;i++)
{
  if(flag)
      sum+=i;
  else
      sum-=i;
  flag=!flag;
}
return sum;
     
      7. 一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少, 用递归算法实现。
答:public class MainClass
                  {
                  public static void Main()
                  {
                  Console.WriteLine(Foo(30));
                  }
                  public static int Foo(int i)
                  {
                  if (i <= 0)
                  return 0;
                  else if(i > 0 && i <= 2)
                  return 1;
                  else return Foo(i -1) + Foo(i - 2);
                  }
                  }

      8.在下面的例子里

Code
class Program
    {
        static void Main(string[] args)
        {
            B _b = new B();
            Console.ReadKey();
        }
    }
    class A
    {
        public A()
        {
            PrintFields();
        }
        public virtual void PrintFields() { }
    }
    class B : A
    {
        int x = 1;
        int y;
        public B()
        {
            y = -1;
        }
        public override void PrintFields()
        {
            Console.WriteLine("x={0},y={1}", x, y);
        }
    }

当使用new B()创建B的实例时,产生什么输出?
答:X=1,Y=0   

    9.short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错?

答:short s1 = 1; s1 = s1 + 1;有错,s1是short型,s1+1是int型,不能显式转化为short型。可修改为s1 =(short)(s1 + 1) 。short s1 = 1; s1 += 1正确。
       
    10.写出输出结果
         
public abstract class A
    {
        public A()
        {
            Console.WriteLine('A');
        }
        public virtual void Fun() 
      {
            Console.WriteLine("A.Fun()");
        }
    }

    public class B : A
    {
        public B()
        {
            Console.WriteLine('B');
        }

        public new void Fun() 
      {
            Console.WriteLine("B.Fun()");
        }

        public static void Main()
        {
            A a = new B();
            a.Fun();
            Console.ReadKey();
        }
    }
A
B
A.Fun()
        第一:调用父类构造函数,第二:调用自身构造函数.

        11.写出输出结果
       
public class A
    {
        public virtual void Fun1(int i)
        {
            Console.WriteLine(i);
        }

        public void Fun2(A a)
        {
            a.Fun1(1);
            Fun1(5);
        }
    }


    public class B : A
    {
        public override void Fun1(int i)
        {
            base.Fun1(i + 1);
        }

        public static void Main()
        {
            B b = new B();
            A a = new A();
            a.Fun2(b);
            b.Fun2(a);
            Console.ReadKey();
        }
    }
  2
    5
    1
    6

12:写一个HTML页面,实现以下功能,左键点击页面时显示“您好”,右键点击时显示“禁止右键”。并在2分钟后自动关闭页面。

答:<script ***script>
setTimeout('window.close();',3000);
function show()
{
if (window.event.button == 1)
{
alert("左");
}
else if (window.event.button == 2)
{
alert("右");
}
}
</script>

13:大概描述一下ASP。NET服务器控件的生命周期
答:初始化 加载视图状态 处理回发数据 加载 发送回发更改通知 处理回发事件 预呈现 保存状态 呈现 处置 卸载
14:程序设计: 猫大叫一声,所有的老鼠都开始逃跑,主人被惊醒。(C#语言)

要求:  1.要有联动性,老鼠和主人的行为是被动的。

          2.考虑可扩展性,猫的叫声可能引起其他联动效应。
Code
public interface Observer
    {
        void Response();    //观察者的响应,如是老鼠见到猫的反映
    }
    public interface Subject
    {
        void AimAt(Observer obs);  //针对哪些观察者,这里指猫的要扑捉的对象---老鼠
    }
    public class Mouse : Observer
    {
        private string name;
        public Mouse(string name, Subject subj)
        {         
            this.name = name;
            subj.AimAt(this);
        }
       
        public void Response()
        {
            Console.WriteLine(name + " attempt to escape!";
        }
    }
    public class Master : Observer
    { 
        public Master(Subject subj)
        {         
            subj.AimAt(this);
        }
       
        public void Response()
        {
            Console.WriteLine("Host waken!";
        } 
    }

    public class Cat : Subject
    {
        private ArrayList observers;
        public Cat()
        { 
            this.observers = new ArrayList();
        }
        public void AimAt(Observer obs)
        {
            this.observers.Add(obs);
        }
        public void Cry()
        {
            Console.WriteLine("Cat cryed!";
            foreach (Observer obs in this.observers)
            {
                obs.Response();
            }
        }
    }
    class MainClass
    {     
        static void Main(string[] args)
        {
            Cat cat = new Cat();
            Mouse mouse1 = new Mouse("mouse1", cat);
            Mouse mouse2 = new Mouse("mouse2", cat);
            Master master = new Master(cat);
            cat.Cry();
        }
    }

      下面的程序运行后:

Code
class Program
    {
        static void Main(string[] args)
        {
            Class1 o1 = new Class1();
            Class1 o2 = new Class1();
           

        }
    }
    class Class1
    {
        private static int count = 0;
        static Class1()
        {
            count++;
        }
        public Class1()
        {
            count++;
        }
    }
请问,o1.Count的值是多少?( C )
A.1        B.2            C.3            D.4
解答:class1在实例化的时候,先运行静态构造函数,然后运行实例构造函数,第二次实例化的时候,由于静态构造函数已经存在,所有直接实例化,它们都共享静态变量count.
(1)用于对静态字段、只读字段等的初始化。                                                               
(2)添加static关键字,不能添加访问修饰符,因为静态构造函数都是私有的。                                    
(3)类的静态构造函数在给定应用程序域中至多执行一次:只有创建类的实例或者引用类的任何静态成员才激发静态构造函数
(4)静态构造函数是不可继承的,而且不能被直接调用。                                                      
(5)如果类中包含用来开始执行的 Main 方法,则该类的静态构造函数将在调用 Main 方法之前执行。                  
    任何带有初始值设定项的静态字段,则在执行该类的静态构造函数时,先要按照文本顺序执行那些初始值设定项。         

(6)如果没有编写静态构造函数,而这时类中包含带有初始值设定的静态字段,那么编译器会自动生成默认的静态构造函数。


原文出处:http://www.cnblogs.com/ASPNET2008/
金鳞岂是池中物,一遇风云便化龙
 

回复:C#经典面试题及答案

支持!
 
1  /  1  页   1 跳转

版权所有 老猫的理想   Sitemap

Powered by Discuz!NT 2.1.202    Copyright © 2001-2008 Comsenz Inc.
Processed in 0.0625 second(s) , 4 queries. 冀ICP备05001409号
返顶部