Csharp/C Sharp/Class Interface/struct
Содержание
- 1 Calling a Function with a Structure Parameter
- 2 C# always creates a structure instance as a value-type variable even using the new operator
- 3 Conversions Between Structs 1
- 4 Conversions Between Structs 2
- 5 Copy a struct
- 6 Define struct and use it
- 7 Defining functions for structs
- 8 Demonstates assignment operator on structures and classes.
- 9 Demonstrate a structure
- 10 demonstrates a custom constructor function for a structure
- 11 demonstrates using a structure to return a group of variables from a function
- 12 Illustrates the use of a struct
- 13 Issue an error message if you do not initialize all of the fields in a structure
- 14 Structs And Enums
- 15 Structs (Value Types):A Point Struct
- 16 Structs (Value Types):Structs and Constructors
- 17 Structures are good when grouping data
Calling a Function with a Structure Parameter
<source lang="csharp"> /* A Programmer"s Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3
- /
// 31 - Interop\Calling Native DLL Functions\Calling a Function with a Structure Parameter // copyright 2000 Eric Gunnerson using System; using System.Runtime.InteropServices; struct Point {
public int x; public int y; public override string ToString() { return(String.Format("({0}, {1})", x, y)); }
} struct Rect {
public int left; public int top; public int right; public int bottom; public override string ToString() { return(String.Format("({0}, {1})\n ({2}, {3})", left, top, right, bottom)); }
} struct WindowPlacement {
public uint length; public uint flags; public uint showCmd; public Point minPosition; public Point maxPosition; public Rect normalPosition; public override string ToString() { return(String.Format("min, max, normal:\n{0}\n{1}\n{2}", minPosition, maxPosition, normalPosition)); }
} public class CallingaFunctionwithaStructureParameterWindow {
[DllImport("user32")] static extern int GetForegroundWindow(); [DllImport("user32")] static extern bool GetWindowPlacement(int handle, ref WindowPlacement wp); public static void Main() { int window = GetForegroundWindow(); WindowPlacement wp = new WindowPlacement(); wp.length = (uint) Marshal.SizeOf(wp); bool result = GetWindowPlacement(window, ref wp); if (result) { Console.WriteLine(wp); } }
}
</source>
C# always creates a structure instance as a value-type variable even using the new operator
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// // ValType.cs -- Demonstrates that C# always creates a structure instance as // a value-type variable even using the new operator. // Compile this program using the following command line: // C:>csc ValType.cs // namespace nsValType {
using System; public struct POINT { public int cx; public int cy; } public class ValType { static public void Main() { POINT point1; point1.cx = 42; point1.cy = 56; ModifyPoint (point1); Console.WriteLine ("In Main() point2 = ({0}, {1})", point1.cx, point1.cy); POINT point2 = new POINT (); // point2.cx = 42; // point2.cy = 56; Console.WriteLine (); ModifyPoint (point2); Console.WriteLine ("In Main() point2 = ({0}, {1})", point2.cx, point2.cy); } static public void ModifyPoint (POINT pt) { pt.cx *= 2; pt.cy *= 2; Console.WriteLine ("In ModifyPoint() pt = ({0}, {1})", pt.cx, pt.cy); } }
}
</source>
Conversions Between Structs 1
<source lang="csharp"> /* A Programmer"s Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3
- /
// 24 - User-Defined Conversions\Conversions Between Structs // copyright 2000 Eric Gunnerson using System; using System.Text; struct RomanNumeral {
public RomanNumeral(short value) { if (value > 5000) throw(new ArgumentOutOfRangeException()); this.value = value; } public static explicit operator RomanNumeral( short value) { RomanNumeral retval; retval = new RomanNumeral(value); return(retval); } public static implicit operator short( RomanNumeral roman) { return(roman.value); } static string NumberString( ref int value, int magnitude, char letter) { StringBuilder numberString = new StringBuilder(); while (value >= magnitude) { value -= magnitude; numberString.Append(letter); } return(numberString.ToString()); } public static implicit operator string( RomanNumeral roman) { int temp = roman.value; StringBuilder retval = new StringBuilder(); retval.Append(RomanNumeral.NumberString(ref temp, 1000, "M")); retval.Append(RomanNumeral.NumberString(ref temp, 500, "D")); retval.Append(RomanNumeral.NumberString(ref temp, 100, "C")); retval.Append(RomanNumeral.NumberString(ref temp, 50, "L")); retval.Append(RomanNumeral.NumberString(ref temp, 10, "X")); retval.Append(RomanNumeral.NumberString(ref temp, 5, "V")); retval.Append(RomanNumeral.NumberString(ref temp, 1, "I")); return(retval.ToString()); } public static implicit operator BinaryNumeral(RomanNumeral roman) { return(new BinaryNumeral((short) roman)); } public static explicit operator RomanNumeral( BinaryNumeral binary) { return(new RomanNumeral((short) binary)); } private short value;
} struct BinaryNumeral {
public BinaryNumeral(int value) { this.value = value; } public static implicit operator BinaryNumeral( int value) { BinaryNumeral retval = new BinaryNumeral(value); return(retval); } public static implicit operator int( BinaryNumeral binary) { return(binary.value); } public static implicit operator string( BinaryNumeral binary) { StringBuilder retval = new StringBuilder(); return(retval.ToString()); } private int value;
} public class ConversionsConversionsBetweenStructs2 {
public static void Main() { RomanNumeral roman = new RomanNumeral(122); BinaryNumeral binary; binary = roman; roman = (RomanNumeral) binary; }
}
</source>
Conversions Between Structs 2
<source lang="csharp"> /* A Programmer"s Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3
- /
// 24 - User-Defined Conversions\Conversions Between Structs // copyright 2000 Eric Gunnerson using System; using System.Text; struct RomanNumeral {
public RomanNumeral(short value) { if (value > 5000) throw(new ArgumentOutOfRangeException()); this.value = value; } public static explicit operator RomanNumeral( short value) { RomanNumeral retval; retval = new RomanNumeral(value); return(retval); } public static implicit operator short( RomanNumeral roman) { return(roman.value); } static string NumberString( ref int value, int magnitude, char letter) { StringBuilder numberString = new StringBuilder(); while (value >= magnitude) { value -= magnitude; numberString.Append(letter); } return(numberString.ToString()); } public static implicit operator string( RomanNumeral roman) { int temp = roman.value; StringBuilder retval = new StringBuilder(); retval.Append(RomanNumeral.NumberString(ref temp, 1000, "M")); retval.Append(RomanNumeral.NumberString(ref temp, 500, "D")); retval.Append(RomanNumeral.NumberString(ref temp, 100, "C")); retval.Append(RomanNumeral.NumberString(ref temp, 50, "L")); retval.Append(RomanNumeral.NumberString(ref temp, 10, "X")); retval.Append(RomanNumeral.NumberString(ref temp, 5, "V")); retval.Append(RomanNumeral.NumberString(ref temp, 1, "I")); return(retval.ToString()); } private short value;
} struct BinaryNumeral {
public BinaryNumeral(int value) { this.value = value; } public static implicit operator BinaryNumeral( int value) { BinaryNumeral retval = new BinaryNumeral(value); return(retval); } public static implicit operator int( BinaryNumeral binary) { return(binary.value); } public static implicit operator string( BinaryNumeral binary) { StringBuilder retval = new StringBuilder(); return(retval.ToString()); } private int value;
} public class ConversionsBetweenStructs1 {
public static void Main() { RomanNumeral roman = new RomanNumeral(12); BinaryNumeral binary; binary = (BinaryNumeral)(int)roman; }
}
</source>
Copy a struct
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Copy a struct.
using System;
// Define a structure. struct MyStruct {
public int x;
}
// Demonstrate structure assignment. public class StructAssignment {
public static void Main() { MyStruct a; MyStruct b; a.x = 10; b.x = 20; Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x); a = b; b.x = 30; Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x); }
}
</source>
Define struct and use it
<source lang="csharp"> /*
* C# Programmers Pocket Consultant * Author: Gregory S. MacBeth * Email: gmacbeth@comporium.net * Create Date: June 27, 2003 * Last Modified Date: */
using System; namespace Client.Chapter_3___Structs__Enums__Arrays_and_Classes {
public struct MyStruct { public int MyInt; public long MyLong; public string MyString; } public class StructsChapter_3___Structs__Enums__Arrays_and_Classes { static void Main(string[] args) { MyStruct TheStruct; TheStruct.MyInt = 0; TheStruct.MyLong = 0; TheStruct.MyString = "Hello World"; } }
}
</source>
Defining functions for structs
<source lang="csharp"> using System; struct Dimensions {
public double Length; public double Width; Dimensions(double length, double width) { Length = length; Width = width; } public double Diagonal { get { return Math.Sqrt(Length * Length + Width * Width); } }
}
</source>
Demonstates assignment operator on structures and classes.
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// // CmpStCls.cs -- Demonstates assignment operator on structures and classes. // Compile this program with the following command line: // C:>csc CmpStCls.cs // namespace nsCompare {
using System;
// // Define a structure containing the x and y coordinates of a point
struct stPoint { public int cx; public int cy; }
// // Define a class containing the x and y coordinates of a point
class clsPoint { public int cx; public int cy; } public class CmpStCls { static public void Main () {
// Declare two structure variables
stPoint spt1, spt2;
// Initialize the members of only one structure
spt1.cx = 42; spt1.cy = 24;
// Assign the first structure to the first
spt2 = spt1;
// Now modify the first structure
spt1.cx = 12; spt1.cy = 18;
// Show the results
Console.WriteLine ("For structures:"); Console.WriteLine ("\tThe point for spt1 is ({0}, {1})", spt1.cx, spt1.cy); Console.WriteLine ("\tThe point for spt2 is ({0}, {1})", spt2.cx, spt2.cy);
// Now do the same thing with instances of the class
clsPoint cpt1, cpt2; cpt1 = new clsPoint();
// Initialize the members of only one class instance
cpt1.cx = 42; cpt1.cy = 24;
// Assign the first class instance to the second
cpt2 = cpt1;
// Modify the first class
cpt1.cx = 12; cpt2.cy = 18;
// Show the results
Console.WriteLine ("\r\nFor structures:"); Console.WriteLine ("\tThe point for cpt1 is ({0}, {1})", cpt1.cx, cpt1.cy); Console.WriteLine ("\tThe point for cpt2 is ({0}, {1})", cpt2.cx, cpt2.cy); } }
}
</source>
Demonstrate a structure
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Demonstrate a structure.
using System;
// Define a structure. struct Book {
public string author; public string title; public int copyright; public Book(string a, string t, int c) { author = a; title = t; copyright = c; }
}
// Demonstrate Book structure. public class StructDemo1 {
public static void Main() { Book book1 = new Book("Herb Schildt", "C# A Beginner"s Guide", 2001); // explicit constructor Book book2 = new Book(); // default constructor Book book3; // no constructor Console.WriteLine(book1.title + " by " + book1.author + ", (c) " + book1.copyright); Console.WriteLine(); if(book2.title == null) Console.WriteLine("book2.title is null."); // now, give book2 some info book2.title = "Brave New World"; book2.author = "Aldous Huxley"; book2.copyright = 1932; Console.Write("book2 now contains: "); Console.WriteLine(book2.title + " by " + book2.author + ", (c) " + book2.copyright); Console.WriteLine();
// Console.WriteLine(book3.title); // error, must initialize first
book3.title = "Red Storm Rising"; Console.WriteLine(book3.title); // now OK }
}
</source>
demonstrates a custom constructor function for a structure
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// tm2.cs - demonstrates a custom constructor function for a structure // Compile this program using the following command line: // D:>csc tm2.cs // namespace nsStructure {
using System; using System.Globalization; struct tm { public tm (DateTime tmVal) { tm_sec = tmVal.Second; tm_min = tmVal.Minute; tm_hour = tmVal.Hour; tm_mday = tmVal.Day; tm_mon = tmVal.Month - 1; tm_year = tmVal.Year - 1900; tm_wday = (int) tmVal.DayOfWeek; tm_yday = tmVal.DayOfYear; TimeZone tz = TimeZone.CurrentTimeZone; tm_isdst = tz.IsDaylightSavingTime (tmVal) == true ? 1 : 0; } public int tm_sec; // Seconds after the minute public int tm_min; // Minutes after the hour public int tm_hour; // Hours since midnight public int tm_mday; // The day of the month public int tm_mon; // The month (January = 0) public int tm_year; // The year (00 = 1900) public int tm_wday; // The day of the week (Sunday = 0) public int tm_yday; // The day of the year (Jan. 1 = 1) public int tm_isdst; // Flag to indicate if DST is in effect public override string ToString() { const string wDays = "SunMonTueWedThuFriSat"; const string months = "JanFebMarAprMayJunJulAugSepOctNovDec"; return (String.Format ("{0} {1} {2,2:00} " + "{3,2:00}:{4,2:00}:{5,2:00} {6}\n", wDays.Substring (3 * tm_wday, 3), months.Substring (3 * tm_mon, 3), tm_mday, tm_hour, tm_min, tm_sec, tm_year + 1900)); } } public class tm2Demo { static public void Main() { DateTime timeVal = DateTime.Now; tm tmNow = new tm (timeVal); Console.WriteLine (tmNow); } }
}
</source>
demonstrates using a structure to return a group of variables from a function
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// tm.cs - demonstrates using a structure to return a group of variables // from a function // // Compile this program using the following command line: // D:>csc tm.cs // namespace nsStructure {
using System; using System.Globalization; public struct tm { public int tm_sec; // Seconds after the minute public int tm_min; // Minutes after the hour public int tm_hour; // Hours since midnight public int tm_mday; // The day of the month public int tm_mon; // The month (January = 0) public int tm_year; // The year (00 = 1900) public int tm_wday; // The day of the week (Sunday = 0) public int tm_yday; // The day of the year (Jan. 1 = 1) public int tm_isdst; // Flag to indicate if DST is in effect } public class tmDemo { static public void Main() { DateTime timeVal = DateTime.Now; tm tmNow = LocalTime (timeVal); string strTime = AscTime (tmNow); Console.WriteLine (strTime); } static public tm LocalTime(DateTime tmVal) { tm time; time.tm_sec = tmVal.Second; time.tm_min = tmVal.Minute; time.tm_hour = tmVal.Hour; time.tm_mday = tmVal.Day; time.tm_mon = tmVal.Month - 1; time.tm_year = tmVal.Year - 1900; time.tm_wday = (int) tmVal.DayOfWeek; time.tm_yday = tmVal.DayOfYear; TimeZone tz = TimeZone.CurrentTimeZone; time.tm_isdst = tz.IsDaylightSavingTime (tmVal) == true ? 1 : 0; return (time); }
// // Returns a string representing a time using UNIX format
static public string AscTime (tm time) { const string wDays = "SunMonTueWedThuFriSat"; const string months = "JanFebMarAprMayJunJulAugSepOctNovDec"; string strTime = String.Format ("{0} {1} {2,2:00} " + "{3,2:00}:{4,2:00}:{5,2:00} {6}\n", wDays.Substring (3 * time.tm_wday, 3), months.Substring (3 * time.tm_mon, 3), time.tm_mday, time.tm_hour, time.tm_min, time.tm_sec, time.tm_year + 1900); return (strTime); } }
}
</source>
Illustrates the use of a struct
<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110
- /
/*
Example5_15.cs illustrates the use of a struct
- /
// declare the Rectangle struct struct Rectangle {
// declare the fields public int Width; public int Height; // define a constructor public Rectangle(int Width, int Height) { this.Width = Width; this.Height = Height; } // define the Area() method public int Area() { return Width * Height; }
}
public class Example5_15 {
public static void Main() { // create an instance of a Rectangle System.Console.WriteLine("Creating a Rectangle instance"); Rectangle myRectangle = new Rectangle(2, 3); // display the values for the Rectangle instance System.Console.WriteLine("myRectangle.Width = " + myRectangle.Width); System.Console.WriteLine("myRectangle.Height = " + myRectangle.Height); // call the Area() method of the Rectangle instance System.Console.WriteLine("myRectangle.Area() = " + myRectangle.Area()); }
}
</source>
Issue an error message if you do not initialize all of the fields in a structure
<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794
- /
// // Struct.cs - Issue an error message if you do not initialize all of // the fields in a structure // // Compile this program with the following command line: // C:>csc Struct.cs // using System; namespace nsStruct {
struct POINT { public int cx; public int cy; public int var; public override string ToString () { return ("(" + cx + ", " + cy + ")"); } } public class StructDemo2 { static public void Main () { POINT pt; pt.cx = 24; pt.cy = 42; Console.WriteLine (pt);
// Console.WriteLine ("(" + pt.cx + ", " + pt.cy + ")");
} }
}
</source>
Structs And Enums
<source lang="csharp"> using System; using System.Collections.Generic; using System.Text; struct Date {
public Date(int ccyy, Month mm, int dd) { this.year = ccyy - 1900; this.month = mm; this.day = dd - 1; } public override string ToString() { return this.month + " " + (this.day + 1) + " " + (this.year + 1900); } private int year; private Month month; private int day;
}
enum Month {
January, February, March, April, May, June, July, August, September, October, November, December
} class Program {
static void Entrance() { Month first = Month.December; Console.WriteLine(first); first++; Console.WriteLine(first); Date defaultDate = new Date(); Console.WriteLine(defaultDate); Date halloween = new Date(2008, Month.October, 31); Console.WriteLine(halloween); } static void Main() { try { Entrance(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
}
</source>
Structs (Value Types):A Point Struct
<source lang="csharp"> using System; struct Point {
public Point(int x, int y) { this.x = x; this.y = y; } public override string ToString() { return(String.Format("({0}, {1})", x, y)); } public int x; public int y;
} public class APointStruct {
public static void Main() { Point start = new Point(5, 5); Console.WriteLine("Start: {0}", start); }
}
</source>
Structs (Value Types):Structs and Constructors
<source lang="csharp"> 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)); }
} public class StructsandConstructors {
public static void Main() { Point[] points = new Point[5]; Console.WriteLine("[2] = {0}", points[2]); }
}
</source>
Structures are good when grouping data
<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852
- /
// Structures are good when grouping data.
using System;
// Define a packet structure. struct PacketHeader {
public uint packNum; // packet number public ushort packLen; // length of packet
}
// Use PacketHeader to create an e-commerce transaction record. class Transaction {
static uint transacNum = 0; PacketHeader ph; // incorporate PacketHeader into Transaction string accountNum; double amount; public Transaction(string acc, double val) { // create packet header ph.packNum = transacNum++; ph.packLen = 512; // arbitrary length accountNum = acc; amount = val; } // Simulate a transaction. public void sendTransaction() { Console.WriteLine("Packet #: " + ph.packNum + ", Length: " + ph.packLen + ",\n Account #: " + accountNum + ", Amount: {0:C}\n", amount); }
}
// Demonstrate Packet public class PacketDemo {
public static void Main() { Transaction t = new Transaction("31243", -100.12); Transaction t2 = new Transaction("AB4655", 345.25); Transaction t3 = new Transaction("8475-09", 9800.00); t.sendTransaction(); t2.sendTransaction(); t3.sendTransaction(); }
}
</source>