In the string method, string operation methods such as ToUpper generate a new string, which increases the running expense. An alternative is to operate strings directly using unmanaged code. For example, replace ToUpper:
Using System;
Public class Test
{
Public static void Main (string [] args)
{
String str = "hello ";
ToUpper (str );
Console. WriteLine (str );
}
Private static unsafe void ToUpper (string str)
{
Fixed (char * pfixed = str)
For (char * p = pfixed; * p! = 0; p ++)
{
* P = char. ToUpper (* p );
}
}
}
Fixed statement:
Format: fixed (type * ptr = expr) statement
It aims to prevent variables from being located by the garbage collector.
Where:
Type is not managed type or void
Ptr is the pointer name.
Expr is an expression that can be implicitly converted to type *.
Statement is an executable statement or block.
The fixed statement can only be used in the context of unsafe. The fixed statement sets a pointer to the managed variable and "locks" the variable during statement execution. If there is no fixed statement, the pointer to the managed variable will have little effect, because garbage collection may be unpredictable to relocate the variable.
After statement is executed, all locked variables are unlocked and restricted by garbage collection. Therefore, do not point to variables other than fixed statements. In unsafe mode, memory can be allocated on the stack. The stack is not restricted by garbage collection, so it does not need to be locked.
However, during compilation, the use of unmanaged code requires/unsafe to pass.