2021年C程序员面试必答.doc

C# 程序员面试必答 1.静态变量和非静态变量区分? 答: 静态变量: 静态变量使用 static 修饰符进行申明 在所属类被装载时创建 经过类进行访问 所属类全部实例同一静态变量全部是同一个值 非静态变量: 不带有 static 修饰符申明变量称做非静态变量 在类被实例化时创建 经过对象进行访问 同一个类不一样实例同一非静态变量能够是不一样值 示例: using System; using System.Collections.Generic; using System.Text; namespace Example01 { class Program { class Class1 { public static String staticStr = amp;quot;Classamp;quot;; public String notstaticStr = amp;quot;Objamp;quot;; } static void Main(string[] args) { //静态变量经过类进行访问,该类全部实例同一静态变量全部是同一个值 Console.WriteLine(amp;quot;Class1s staticStr: {0}amp;quot;, Class1.staticStr); Class1 tmpObj1 = new Class1(); tmpObj1.notstaticStr = amp;quot;tmpObj1amp;quot;; Class1 tmpObj2 = new Class1(); tmpObj2.notstaticStr = amp;quot;tmpObj2amp;quot;; //非静态变量经过对象进行访问,不一样对象同一非静态变量能够有不一样值 Console.WriteLine(amp;quot;tmpObj1s notstaticStr: {0}amp;quot;, tmpObj1.notstaticStr); Console.WriteLine(amp;quot;tmpObj2s notstaticStr: {0}amp;quot;, tmpObj2.notstaticStr); Console.ReadLine(); } } } 复制代码 结果: Class1s staticStr: Class tmpObj1s notstaticStr: tmpObj1 tmpObj2s notstaticStr: tmpObj2 2.const 和 static readonly 区分? 答: const 用 const 修饰符申明组员叫常量,是在编译期初始化并嵌入到用户端程序 static readonly 用 static readonly 修饰符申明组员仍然是变量,只不过含有和常量类似使用方法:经过类进行访问、初始化后不能够修改。但和常量不一样是这种变量是在运行期初始化 示例: 测试类: using System; using System.Collections.Generic; using System.Text; namespace Example02Lib { public class Class1 { public const String strConst = amp;quot;Constamp;quot;; public static readonly String strStaticReadonly = amp;quot;StaticReadonlyamp;quot;; //public const String strConst = amp;quot;Const Changedamp;quot;; //public static readonly String strStaticReadonly = amp;quot;StaticReadonly Changedamp;quot;; }//5-1-a-s-p-x } 复制代码 用户端代码: using System; using System.Collections.Generic; using System.Text;

文档评论(0)

1亿VIP精品文档

相关文档