Материал из .Net Framework эксперт
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Fraction struct
using System;
public struct Fraction {
public Fraction(double _divisor, double _dividend) {
divisor = _divisor;
dividend = _dividend;
}
public double quotient {
get {
return divisor / dividend;
}
}
private double divisor;
private double dividend;
}
public class Calculate {
public static void Main() {
Fraction number = new Fraction(4, 5);
Console.WriteLine("{0}", number.quotient);
}
}
Struct constructor with parameters
using System;
struct Point
{
public int x;
public int y;
public Point(int a, int b)
{
x = a;
y = b;
}
}
class MainClass
{
static void Main()
{
Point p1 = new Point();
Point p2 = new Point(5, 10);
Console.WriteLine("{0},{1}", p1.x, p1.y);
Console.WriteLine("{0},{1}", p2.x, p2.y);
}
}
0,0
5,10
Structs with constructors
using System;
struct Point
{
int x;
int y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override string ToString()
{
return(String.Format("({0}, {1})", x, y));
}
}
class MainClass
{
public static void Main()
{
Point[] points = new Point[5];
Console.WriteLine("[2] = {0}", points[2]);
}
}
[2] = (0, 0)
Use method to init struct member variables
using System;
public struct Simple {
public int i;
private string s;
public void init( ) {
i = 10;
s = "Hello";
}
}
public class MainClass {
public static void Main( ) {
Simple simple = new Simple();
simple.init( );
}
}