1. Application of MessageBox:
MessageBox. Show ("disconnected successfully! "," Prompt ", messageboxbuttons. OK, messageboxicon. information );
2. convert a string to a byte array:
Declare byte array byte [] strbyte = byte [10]
# Region String Conversion to byte array
Private byte [] stringtobyte (string S)
{
Arraylist Al = new arraylist ();
For (INT I = 0; I <S. length; I ++)
{
Al. Add (byte) s [I]);
}
Return (byte []) Al. toarray (system. type. GetType ("system. Byte "));
}
# Endregion
3. Convert the byte array to a string:
System. Text. encoding. Default. getstring ();
Convert a string to a byte array: the byte array may not be converted into a string. The system. Text. encoding. Default. getbytes () method can be used unless it stores the correct string encoding ();
4. interchange between struct and byte Arrays:
When writing a C # TCP communication program, when sending data, only byte Arrays can be sent, which is difficult to process.
Communication, many transfer struct. In VC, a char [] array can be converted into a struct, and a two-byte array cannot be converted directly.
The following solution:
(1) define struct:
// Namespace
Using system. runtime. interopservices;
// Note that this attribute cannot be less
[Structlayoutattribute (layoutkind. Sequential, charset = charset. ANSI, pack = 1)]
Struct teststruct
{
Public int C;
// String. sizeconst is the maximum length of the string.
[Financialas (unmanagedtype. byvaltstr, sizeconst = 256)]
Public String STR;
// Int array. sizeconst indicates the number of arrays.
// The byte array must be initialized before use.
// The length of the array must be the same as that of sizeconst, for example, test = new int [6];
[Financialas (unmanagedtype. byvalarray, sizeconst = 6)]
Public int [] test;
}
(2) convert struct to byte array:
/** // <Summary>
/// Convert struct to byte array
/// </Summary>
/// <Param name = "structobj"> struct to be converted </param>
/// <Returns> converted byte array </returns>
Public static byte [] structtobytes (Object structobj)
{
// Obtain the size of the struct.
Int size = marshal. sizeof (structobj );
// Create a byte array
Byte [] bytes = new byte [size];
// Allocate the memory space of the struct size
Intptr structptr = marshal. allochglobal (size );
// Copy the struct to the allocated memory space
Marshal. structuretoptr (structobj, structptr, false );
// Copy from memory space to byte array
Marshal. Copy (structptr, bytes, 0, size );
// Release memory space
Marshal. freehglobal (structptr );
// Returns the byte array.
Return bytes;
}
(3) convert byte array to struct:
/** // <Summary>
/// Convert byte array to struct
/// </Summary>
/// <Param name = "bytes"> byte array </param>
/// <Param name = "type"> struct type </param>
/// <Returns> converted struct </returns>
Public static object bytestostuct (byte [] bytes, type)
{
// Obtain the size of the struct.
Int size = marshal. sizeof (type );
// The byte array length is smaller than the size of the struct.
If (size> bytes. length)
{
// Return null
Return NULL;
}
// Allocate the memory space of the struct size
Intptr structptr = marshal. allochglobal (size );
// Copy the byte array to the allocated memory space
Marshal. Copy (bytes, 0, structptr, size );
// Convert the memory space to the target struct
Object OBJ = marshal. ptrtostructure (structptr, type );
// Release memory space
Marshal. freehglobal (structptr );
// Returns the struct.
Return OBJ;
}
5. Declared struct serializable
[Serializable] // indicates serializable
[Structlayout (layoutkind. Sequential, pack = 1)] // align by 1 byte
Public struct Operator
6. Relationship between C # And C ++ Data Types
Data Type ing between C ++ and C #
API data type
Type description
C # type
API data type
Type description
C # type
Word
16-bit unsigned integer
Ushort
Char
Character
Char
Long
32-bit unsigned integer
Int
Dwordlong
64-bit long integer
Long
DWORD
32-bit unsigned integer
Uint
HDC
Device description table handle
Int
Handle
Handle, 32-bit integer
Int
Hgdiobj
GDI object handle
Int
Uint
32-bit unsigned integer
Uint
Hinstance
Instance handle
Int
Bool
32-bit Boolean integer
Bool
Hwm
Window handle
Int
Lpstr
32-bit pointer to a character
String
Hparam
32-bit message Parameters
Int
Lpcstr
32-bit pointer to a common character
String
Lparam
32-bit message Parameters
Int
Byte
Bytes
Byte
Wparam
32-bit message Parameters
Int
7. Int [] I _maincopy = new int [] {0}; declares the int array and assigns a value to 0 to the array.
Math. Round () function in 8. C #
Math. Round (2.5, 0) = 2;
This function is not rounded to five, but to six to five,
If the rounding position is 5, the last digit after the rounding is an even number. This is an international convention.
Currently, five projects are required. solution:
The current practice is:
For example: (3.45*10 + 0.5) Get an integer and divide it by 10.
9. C # Time Processing (datetime and timespan)
// Obtain the last day of a month
// Method 1: calculate the number of days of the month, and the number of days plus the year + month. The example shows the last day of the month.
Private void getlastdateformonth (datetime dtstart, out datetime dtend)
{
Int dtyear, dtmonth;
Dtstart = datetime. now;
Dtyear = dtstart. Year;
Dtmonth = dtstart. month;
Int monthcount = datetime. daysinmonth (dtyear, dtmonth); // calculates the number of days in a month.
Dtend = convert. todatetime (dtyear. tostring () + "-" + dtmonth. tostring () + "-" + monthcount );
}
// Method 2: retrieve the first day of the next month.
Private void getlastdateformonth (datetime dtstart, out datetime dtend)
{
Int dtyear, dtmonth;
Dtstart = datetime. Now. addmonths (1); // Add 1 to the month
Dtyear = dtstart. Year;
Dtmonth = dtstart. month;
Dtend = convert. todatetime (dtyear. tostring () + "-" + dtmonth. tostring () + "-" + "1 "). adddays (-1); // retrieve the first day of the next month for one day
}
Ii. Calculation of time difference
Method 1: Use timespan and introduce the usage of timespan.
Related attributes and functions
Add: adds the value to another timespan value.
Days: returns the timespan value calculated by the number of days.
Duration: gets the absolute value of timespan.
Hours: returns the hourly timespan value.
Milliseconds: returns the timespan value in milliseconds.
Minutes: returns the timespan value calculated in minutes.
Negate: returns the opposite number of the current instance.
Seconds: returns the timespan value calculated in seconds.
Subtract: Subtract another timespan value from it.
Ticks: the number of tick values returned for timespan.
Totaldays: returns the number of days indicated by the timespan value.
Totalhours: returns the number of hours represented by the timespan value.
Totalmilliseconds: the number of milliseconds in which the timespan value is returned.
Totalminutes: returns the number of minutes represented by the timespan value.
Totalseconds: returns the number of seconds represented by the timespan value.
Simple Example:
Datetime d1 = new datetime );
Datetime D2 = new datetime );
Timespan D3 = d2.subtract (D1 );
Lbtime. Text = "difference :"
+ D3.days. tostring () + "day"
+ D3.hours. tostring () + "hour"
+ D3.minutes. tostring () + "Minute"
+ D3.seconds. tostring () + "seconds ";
Method 2: Use the datediff function in SQL
Usage: datediff (datepart, startdate, enddate)
It can help you get the time difference in various forms you want, such as how many days, how many hours, and how many minutes are separated. The specific format is as follows:
Abbreviation of date
Year YY, yyyy
Quarter QQ, Q
Month mm, m
Dayofyear dy, y
Day DD, d
Week wk, WW
Hour HH
Minute Mi, n
Second SS, S
Millisecond MS
For example, datediff (MI, dtoptime, dtend) can retrieve the total number of minutes of time difference between them, which has been converted for you. It is particularly useful for specifying the unit, time, minute, and second.
3 calculate the difference between two days of working days (reprinted: http://wrfwjn.blog.hexun.com/482517_d.html)
/// <Summary>
/// Calculate the number of working days between two dates
/// </Summary>
/// <Param name = "dtstart"> Start date </param>
/// <Param name = "dtend"> end date </param>
/// <Returns> int </returns>
Public int calculateworkingdays (datetime dtstart, datetime dtend)
{
Int COUNT = 0;
For (datetime dttemp = dtstart; dttemp <dtend; dtemp = dttemp. adddays (1 ))
{
// If (dttemp. dayofweek! = Dayofweek. Saturday & dttemp. dayofweek! = Dayofweek. Sunday)
//{
// Count ++;
//}
Count ++;
}
Return count;
}
Datetime is the built-in event type, and timespan is the built-in event interval type.
Perform operations on two datetime-type variables to obtain data of the timespan type.
Datetime. Now is a read-only attribute that returns the current time, type: datetime
Timespan: Calculate the interval between two specified dates based on the input date.
Syntax: String timespan ('escape characters', 'compared date', 'destination compared date ')
Return Value: character
Parameter description:
Escape Character: Characters of the input type with different formatting characters, as shown in the content description. The formatting characters in the input characters are formatted and output. Other characters that are not formatted are output according to the corresponding position. 'Date to be compared ': the input type is a character and the content of the character in the date format to be compared. 'Destination comparison date': the input type is a character used to compare the content of the characters in the target date format.
Description: Calculate the interval between two specified dates based on the input date.
Escape Character Description: T: obtains the difference value represented by the difference scale between two dates. (Positive or negative) D: returns the whole number of days for the difference between two dates. (Positive or negative) h: obtains the hour of the difference between two dates. (Positive or negative) U: returns the number of milliseconds for the difference between two dates. (Positive or negative) M: returns the number of minutes of the difference between two dates. (Positive or negative) S: returns the integer number of seconds between two dates. (Positive or negative) D: gets the difference between two dates in the whole day and the decimal part of the day. (Positive or negative) h: obtains the difference between two dates expressed in the fractional part of the hour and hour. (Positive or negative) U: obtains the difference between the entire millisecond count and the fractional part of the millisecond between two dates. (Positive or negative) M: gets the difference between two dates in the whole minute and minute decimal part. (Positive or negative) S: gets the difference between two dates in the integer and second decimal part. (Positive or negative)
10. automatically perform the C # function on the text Branch
A fairly simple C # function implements code snippets, which are used to automatically break a long winform tooltip by dividing lines and breaking lines according to the minimum line length (which will exceed the minimum line length.
Private string multiplinestring (string instr, int line_length)
{
String remain = instr, multi_line = "";
While (remain. length> line_length)
{
Int space_pos = remain. indexof ('', line_length );
If (space_pos =-1)
Break;
Multi_line + = remain. substring (0, space_pos) + "/R/N ";
Remain = remain. substring (space_pos + 1 );
}
Return multi_line + remain;
}
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/kaola2599/archive/2009/06/25/4294633.aspx