Here are some samples I wrote for self reminders.
This sample show a few example about the use of properties, methods overriding, operators overriding.
using System;
namespace StructureCircle {
struct Cycle { // Private fields int _val, _min, _max;
// Constructor public Cycle(int min, int max) { _val = min; _min = min; _max = max; }
public int Value { get { return _val; } set { if (value > _max) this.Value = value - _max + _min - 1;
else { if (value < _min) this.Value = _min - value + _max - 1; else _val = value; } } }
public override string ToString() { return Value.ToString(); }
public int ToInteger() { return Value; }
public static Cycle operator +(Cycle arg1, int arg2) { arg1.Value += arg2; return arg1; }
public static Cycle operator -(Cycle arg1, int arg2) { arg1.Value -= arg2; return arg1; } }
class StructCircle { static void Main(string[] args) { Cycle degrees = new Cycle(0, 359); Cycle quarters = new Cycle(1, 4); for (int i = 0; i <= 8; i++) { degrees += 90; quarters += 1; Console.WriteLine("degrees = {0}, quarters = {1}", degrees, quarters); } Console.ReadKey(); } } } | |
Result: degrees = 90, quarters = 2 |
This sample shows overriding the ToString() method in a Person struct.
using System;
namespace StructurePerson { class StructPerson { struct Person { public string firstName; public string lastName; public int age; public enum Gender { Meal, Femeal }; public Gender gender;
public Person(string _firstName, string _lastName, int _age, Gender _gender) { firstName = _firstName; lastName = _lastName; age = _age; gender = _gender; }
public override string ToString() { return firstName + " " + lastName + " (" + gender + "), age " + age; } }
static void Main(string[] args) { Person p = new Person("Lin","Ben",100,Person.Gender.Meal); Console.WriteLine(p); Console.WriteLine(p.ToString()); Console.ReadKey(); } } } | |
Result: File write to text.txt |
No comments:
Post a Comment