Экземпляры класса, вызов переопределенного метода - C#
Формулировка задачи:
как лучше вызвать переопределенный метод?
или через статический метод(так как сделал ниже в программе)?
Листинг программы
- Console.WriteLine(m1.ToString());
Листинг программы
- class MyClass
- {
- public string Name { get; set; }
- public int Age { get; set; }
- public MyClass(string name, int age)
- {
- Name = name;
- Age = age;
- }
- public override string ToString()
- {
- return string.Format(" Имя: {0}\tВозраст: {1}", Name, Age);
- }
- }
- class Program
- {
- static void Main()
- {
- MyClass m1 = new MyClass("Vlad", 10);
- Console.WriteLine(m1.ToString());
- MyClass m2 = m1;
- m2.Name = "Tom";
- m2.Age = 15;
- Display(m1);
- Display(m2);
- Console.ReadKey();
- }
- static void Display(MyClass m1 )
- {
- Console.WriteLine(m1);
- }
- }
Решение задачи: «Экземпляры класса, вызов переопределенного метода»
textual
Листинг программы
- .method private hidebysig static void Main() cil managed
- {
- // Code size 70 (0x46)
- .maxstack 3
- .locals init ([0] class ClassLibrary1.MyClass m1,
- [1] class ClassLibrary1.MyClass m2)
- .line 27,27 : 9,10 ''
- IL_0000: nop
- .line 28,28 : 13,50 ''
- IL_0001: ldstr "Vlad"
- IL_0006: ldc.i4.s 10
- IL_0008: newobj instance void ClassLibrary1.MyClass::.ctor(string,
- int32)
- IL_000d: stloc.0
- .line 29,29 : 13,46 ''
- IL_000e: ldloc.0
- IL_000f: callvirt instance string [mscorlib]System.Object::ToString()
- IL_0014: call void [mscorlib]System.Console::WriteLine(string)
- IL_0019: nop
- .line 31,31 : 13,29 ''
- IL_001a: ldloc.0
- IL_001b: stloc.1
- .line 32,32 : 13,29 ''
- IL_001c: ldloc.1
- IL_001d: ldstr "Tom"
- IL_0022: callvirt instance void ClassLibrary1.MyClass::set_Name(string)
- IL_0027: nop
- .line 33,33 : 13,25 ''
- IL_0028: ldloc.1
- IL_0029: ldc.i4.s 15
- IL_002b: callvirt instance void ClassLibrary1.MyClass::set_Age(int32)
- IL_0030: nop
- .line 34,34 : 13,25 ''
- IL_0031: ldloc.0
- IL_0032: call void ClassLibrary1.Program::Display(class ClassLibrary1.MyClass)
- IL_0037: nop
- .line 35,35 : 13,25 ''
- IL_0038: ldloc.1
- IL_0039: call void ClassLibrary1.Program::Display(class ClassLibrary1.MyClass)
- IL_003e: nop
- .line 37,37 : 13,31 ''
- IL_003f: call valuetype [mscorlib]System.ConsoleKeyInfo [mscorlib]System.Console::ReadKey()
- IL_0044: pop
- .line 38,38 : 9,10 ''
- IL_0045: ret
- } // end of method Program::Main
- .method private hidebysig static void Display(class ClassLibrary1.MyClass m1) cil managed
- {
- // Code size 9 (0x9)
- .maxstack 8
- .line 40,40 : 9,10 ''
- IL_0000: nop
- .line 41,41 : 13,35 ''
- IL_0001: ldarg.0
- IL_0002: call void [mscorlib]System.Console::WriteLine(object)
- IL_0007: nop
- .line 42,42 : 9,10 ''
- IL_0008: ret
- } // end of method Program::Display
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д