C#学习笔记 from 2006.10
1.类间变量的使用
c#中没有全局变量的概念,需要全局访问的变量可以放在一个类中,然后跨类访问变量即可。例:
建立一code.cs文件,输入类:
public class CmdSet
{
public static string ss = "123"; //注意必须使用public static作变量定义
}
在别的地方调用时,只需要引用code.cs中的namespace,并按此格式使用变量ss : CmdSet.ss
2.数组的复制
有时候需要将几个数组的值整合到一个数组中,这个时候可以用数组的复制功能:Array.CopyTo
int i;
string t1 = "";
int[] bc1 = {10,20};
int[] bc2 = {30,40};
int[] bc3 = new int[4];
bc1.CopyTo(bc3,0);
bc2.CopyTo (bc3,bc1.Length);
for (i=0; i<4; i++)
{
textBox1.AppendText (bc3[i].ToString () + "/n");
}
bc3的值为{10,20,30,40};
3.按窗口1中的一个按钮,打开窗口2
private void button7_Click(object sender, System.EventArgs e)
{
Form Form3 = new Form();
Form3.Show();
}
4.位移操作的说明
The left-shift operator (<<) shifts its first operand left by the number of bits specified by its second operand.
expr << count
Where:
-
expr
- An expression of type int, uint, long, or ulong; the value to be shifted. count
- An expression of type int; the shift count.
Remarks
If expr is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of count (count & 0x1f).
If expr is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of count (count & 0x3f).
The high-order bits of expr are discarded and the low-order empty bits are zero-filled. Shift operations never cause overflows.
User-defined types can overload the << operator (see operator); the type of the first operand must be the user-defined type, and the type of the second operand must be int.
Example
// cs_operator_left_shift.cs using System; class Test { public static void Main() { int i = 1; long lg = 1; Console.WriteLine("0x{0:x}", i << 1); Console.WriteLine("0x{0:x}", i << 33); Console.WriteLine("0x{0:x}", lg << 33); } }
Output
0x2 0x2 0x200000000
Note that i<<1
and i<<33
give the same result, because 1 and 33 have the same low-order five bits.
5.BIT位计算
example1
BitArray ba = new BitArray(new int[]{0x3});
bool bit1 = ba.Get(0);
bool bit2 = ba.Get(1);
bool bit3 = ba.Get(2);
bool bit4 = ba.Get(3);
example2
public boolean HasBit(numValue, bitValue)
{
return ( numValue & bitValue != 0 );
}
bool hasBit1 = HasBit(myHex, 0x01);
bool hasBit2 = HasBit(myHex, 0x02);
bool hasBit3 = HasBit(myHex, 0x04);
bool hasBit4 = HasBit(myHex, 0x08);
bool hasBit5 = HasBit(myHex, 0x10);
bool hasBit6 = HasBit(myHex, 0x11);
Or, if you'd rather reference the bit-number instead of the bit-value:
public boolean HasBitNum(int numValue, int bitNum)
{
int bitValue = ( 1 << (intBitNum - 1) );
return ( numValue & bitValue != 0 );
}
bool hasBit1 = HasBitNum(myHex, 1);
bool hasBit2 = HasBitNum(myHex, 2);
bool hasBit3 = HasBitNum(myHex, 3);
bool hasBit4 = HasBitNum(myHex, 4);