Tag Archives: c#

程序人生

C++ 运算符优先级列表

http://www.cppreference.com/operator_precedence.html

Precedence Operator Description Example Associativity
1 ()
[]
->
.
::
++
Grouping operator
Array access
Member access from a pointer
Member access from an object
Scoping operator
Post-increment
Post-decrement
(a + b) / 4;
array[4] = 2;
ptr->age = 34;
obj.age = 34;
Class::age = 2;
for( i = 0; i < 10; i++ ) …
for( i = 10; i > 0; i– ) …
left to right
2 !
~
++

-
+
*
&
(type)
sizeof
Logical negation
Bitwise complement
Pre-increment
Pre-decrement
Unary minus
Unary plus
Dereference
Address of
Cast to a given type
Return size in bytes
if( !done ) …
flags = ~flags;
for( i = 0; i < 10; ++i ) …
for( i = 10; i > 0; –i ) …
int i = -1;
int i = +1;
data = *ptr;
address = &obj;
int i = (int) floatNum;
int size = sizeof(floatNum);
right to left
3 ->*
.*
Member pointer selector
Member pointer selector
ptr->*var = 24;
obj.*var = 24;
left to right
4 *
/
%
Multiplication
Division
Modulus
int i = 2 * 4;
float f = 10 / 3;
int rem = 4 % 3;
left to right
5 +
-
Addition
Subtraction
int i = 2 + 3;
int i = 5 – 1;
left to right
6 <<
>>
Bitwise shift left
Bitwise shift right
int flags = 33 << 1;
int flags = 33 >> 1;
left to right
7 <
<=
>
>=
Comparison less-than
Comparison less-than-or-equal-to
Comparison greater-than
Comparison geater-than-or-equal-to
if( i < 42 ) …
if( i <= 42 ) …
if( i > 42 ) …
if( i >= 42 ) …
left to right
8 ==
!=
Comparison equal-to
Comparison not-equal-to
if( i == 42 ) …
if( i != 42 ) …
left to right
9 & Bitwise AND flags = flags & 42; left to right
10 ^ Bitwise exclusive OR flags = flags ^ 42; left to right
11 | Bitwise inclusive (normal) OR flags = flags | 42; left to right
12 && Logical AND if( conditionA && conditionB ) … left to right
13 || Logical OR if( conditionA || conditionB ) … left to right
14 ? : Ternary conditional (if-then-else) int i = (a > b) ? a : b; right to left
15 =
+=
-=
*=
/=
%=
&=
^=
|=
<<=
>>=
Assignment operator
Increment and assign
Decrement and assign
Multiply and assign
Divide and assign
Modulo and assign
Bitwise AND and assign
Bitwise exclusive OR and assign
Bitwise inclusive (normal) OR and assign
Bitwise shift left and assign
Bitwise shift right and assign
int a = b;
a += 3;
b -= 4;
a *= 5;
a /= 2;
a %= 3;
flags &= new_flags;
flags ^= new_flags;
flags |= new_flags;
flags <<= 2;
flags >>= 2;
right to left
16 , Sequential evaluation operator for( i = 0, j = 0; i < 10; i++, j++ ) … left to right
程序人生

c#笔试参考附答案

1. 简述 private、 protected、 public、 internal 修饰符的访问权限。
答 . private :     私有成员, 在类的内部才可以访问。
       protected : 保护成员,该类内部和继承类中可以访问。
       public :      公共成员,完全公开,没有访问限制。
       internal:     在同一命名空间内可以访问。

2 .列举ASP.NET 页面之间传递值的几种方式。
答. 1.使用QueryString,    如….?id=1; response. Redirect()….
      2.使用Session变量
      3.使用Server.Transfer

3. 一列数的规则如下: 1、1、2、3、5、8、13、21、34……    求第30位数是多少, 用递归算法实现。
答:public class MainClass
      {
          public static void Main()   
          {
              Console.WriteLine(Foo(30));
          }
          public static int Foo(int i)
          {
              if (i <= 0)
                  return 0;
              else if(i > 0 && i <= 2)
                  return 1;
              else return Foo(i -1) + Foo(i – 2);
          }
      }

4.C#中的委托是什么?事件是不是一种委托?
答 :      
委托可以把一个方法作为参数代入另一个方法。
委托可以理解为指向一个函数的引用。
是,是一种特殊的委托

5.override与重载的区别
答 :
override 与重载的区别。重载是方法的名称相同。参数或参数类型不同,进行多次重载以适应不同的需要
Override 是进行基类中函数的重写。为了适应需要。

6.如果在一个B/S结构的系统中需要传递变量值,但是又不能使用Session、Cookie、Application,您有几种方法进行处理?
答 :
this.Server.Transfer

7.请编程遍历页面上所有TextBox控件并给它赋值为string.Empty?
答:
        foreach (System.Windows.Forms.Control control in this.Controls)
        {
if (control is System.Windows.Forms.TextBox)
{
      System.Windows.Forms.TextBox tb = (System.Windows.Forms.TextBox)control ;
      tb.Text = String.Empty ;
}
        }

8.请编程实现一个冒泡排序算法?
答:
          int [] array = new int [*] ;
int temp = 0 ;
for (int i = 0 ; i < array.Length – 1 ; i++)
{
for (int j = i + 1 ; j < array.Length ; j++)
{
if (array[j] < array[i])
{
temp = array[i] ;
array[i] = array[j] ;
array[j] = temp ;
}
}
}

9.描述一下C#中索引器的实现过程,是否只能根据数字进行索引?
答:不是。可以用任意类型。

10.求以下表达式的值,写出您想到的一种或几种实现方法: 1-2+3-4+……+m
答:
      int Num = this.TextBox1.Text.ToString() ;
int Sum = 0 ;
for (int i = 0 ; i < Num + 1 ; i++)
{
if((i%2) == 1)
{
Sum += i ;
}
else
{
Sum = Sum    – I ;
}
}
System.Console.WriteLine(Sum.ToString());
System.Console.ReadLine() ;

11.用.net做B/S结构的系统,您是用几层结构来开发,每一层之间的关系以及为什么要这样分层?
答:一般为3层
          数据访问层,业务层,表示层。
          数据访问层对数据库进行增删查改。
          业务层一般分为二层,业务表观层实现与表示层的沟通,业务规则层实现用户密码的安全等。
          表示层为了与用户交互例如用户添加表单。
优点:    分工明确,条理清晰,易于调试,而且具有可扩展性。
缺点:    增加成本。

12.在下面的例子里
       using System;
       class A
       {
            public A()
             {
                  PrintFields();
             }
            public virtual void PrintFields(){}
        }
        class B:A
        {
             int x=1;
             int y;
             public B()
     {
                 y=-1;
             }
             public override void PrintFields()
             {
                 Console.WriteLine("x={0},y={1}",x,y);
             }
当使用new B()创建B的实例时,产生什么输出?
答:X=1,Y=0;x= 1 y = -1

13.什么叫应用程序域?
答:应用程序域可以理解为一种轻量级进程。起到安全的作用。占用资源小。

14.CTS、CLS、CLR分别作何解释?
答:CTS:通用语言系统。CLS:通用语言规范。CLR:公共语言运行库。

15.什么是装箱和拆箱?
答:从值类型接口转换到引用类型装箱。从引用类型转换到值类型拆箱。

16.什么是受管制的代码?
答:unsafe:非托管代码。不经过CLR运行。

17.什么是强类型系统?
答:RTTI:类型识别系统。

18.net中读写数据库需要用到那些类?他们的作用?
答:DataSet:数据存储器。
      DataCommand:执行语句命令。
      DataAdapter:数据的集合,用语填充。

19.ASP.net

程序人生

C# 转义字符

几个转义字符,可能多用几次也不用专门查了,记录一份:

转义符     字符名
 
\’    单引号
 
\"   双引号
 
\\  反斜杠
 
\0  空字符
 
\a  感叹号
 
\b   退格
 
\f  换页
 
\n  新行
 
\r  回车
 
\t   水平 tab
 
\v     垂直tab

程序人生

在C#里面判断一个String是否为数字

有时候为了判断一个字符串是否为数字,不是数字的怎么处理,比如在程序中传id进行查询等。大致有以下几种做法:

一、进行try catch异常处理(效率低)
        示例:
         private bool IsNumberic(string oText)
        {
          try
         {
                  int var1=Convert.ToInt32 (oText);
                  return true;
         }
          catch
         {
                  return false;
         }
     }

二、正则表达式判断(注意添加引用 System.Text.RegularExpressions)
        示例:
         a)
    public bool IsNumber(String strNumber)
    {
           Regex objNotNumberPattern=new Regex("[^0-9.-]");
           Regex objTwoDotPattern=new Regex("[0-9]*[.][0-9]*[.][0-9]*");
           Regex objTwoMinusPattern=new Regex("[0-9]*[-][0-9]*[-][0-9]*");
           String strValidRealPattern="^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
           String strValidIntegerPattern="^([-]|[0-9])[0-9]*$";
           Regex objNumberPattern =new Regex("(" + strValidRealPattern +")|(" + strValidIntegerPattern + ")");

           return !objNotNumberPattern.IsMatch(strNumber) &&
                  !objTwoDotPattern.IsMatch(strNumber) &&
                  !objTwoMinusPattern.IsMatch(strNumber) &&
                  objNumberPattern.IsMatch(strNumber);
    }

    b)
    public static bool IsNumeric(string value)
    {
         return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
    }
    public static bool IsInt(string value)
    {
         return Regex.IsMatch(value, @"^[+-]?\d*$");
    }
    public static bool IsUnsign(string value)
    {
         return Regex.IsMatch(value, @"^\d*[.]?\d*$");
    }

三、遍历
        示例:
       public bool isnumeric(string str)
       {
                char[] ch=new char[str.Length];
                ch=str.ToCharArray();
                for(int i=0; i< str.Length; i++)
                {
                        if(ch[i]<48 || ch[i]>57)
                        return false;
                 }
                return true;
         }
      
四、改写vb的IsNumeric源代码 (-_-!)
        示例:
       //主调函数
       public static bool IsNumeric(object Expression)
       {
      bool flag1;
      IConvertible convertible1 = null;
      if (Expression is IConvertible)
      {
            convertible1 = (IConvertible) Expression;
      }
      if (convertible1 == null)
      {
            if (Expression is char[])
            {
                  Expression = new string((char[]) Expression);
            }
            else
            {
                  return false;
            }
      }
      TypeCode code1 = convertible1.GetTypeCode();
      if ((code1 != TypeCode.String) && (code1 != TypeCode.Char))
      {
            return Utils.IsNumericTypeCode(code1);
      }
      string text1 = convertible1.ToString(null);
      try
      {
            long num2;
            if (!StringType.IsHexOrOctValue(text1, ref num2))
            {
                  double num1;
                  return DoubleType.TryParse(text1, ref num1);
            }
            flag1 = true;
      }
      catch (Exception)
      {
            flag1 = false;
>      }
      return flag1;
       }
      //子函数
       // return Utils.IsNumericTypeCode(code1);
       internal static bool IsNumericTypeCode(TypeCode TypCode)
       {
      switch (TypCode)
      {
            case TypeCode.Boolean:
            case TypeCode.Byte:
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
            case TypeCode.Single:
            case TypeCode.Double:
            case TypeCode.Decimal:
            {
                  return true;
            }
            case TypeCode.Char:
            case TypeCode.SByte:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
            {
                  break;
            }
      }
      return false;
       }
 

       //—————–
       //StringType.IsHexOrOctValue(text1, ref num2))
       internal static bool IsHexOrOctValue(string Value, ref long i64Value)
       {
      int num1;
      int num2 = Value.Length;
      while (num1 < num2)
      {
            char ch1 = Value[num1];
            if (ch1 == ‘&’)
            {
                  ch1 = char.ToLower(Value[num1 + 1], CultureInfo.InvariantCulture);
                  string text1 = StringType.ToHalfwidthNumbers(Value.Substring(num1 + 2));
                  if (ch1 == ‘h’)
                  {
                        i64Value = Convert.ToInt64(text1, 0×10);
                  }
                  else if (ch1 == ‘o’)
                  {
                        i64Value = Convert.ToInt64(text1, 8);
                  }
                  else
                  {
                        throw new FormatException();
                  }
                  return true;
            }
            if ((ch1 != ‘ ‘) && (ch1 != ‘\u3000′))
            {
                  return false;
            }
            num1++;
      }
      return false;
       }
       //—————————————————-
       // DoubleType.TryParse(text1, ref num1);
       internal static bool TryParse(string Value, ref double Result)
       {
      bool flag1;
      CultureInfo info1 = Utils.GetCultureInfo();
      NumberFormatInfo info3 = info1.NumberFormat;
      NumberFormatInfo info2 = DecimalType.GetNormalizedNumberFormat(info3);
      Value = StringType.ToHalfwidthNumbers(Value, info1);
      if (info3 == info2)
      {
            return double.TryParse(Value, NumberStyles.Any, info2, out Result);
      }
      try
      {
            Result = double.Parse(Value, NumberStyles.Any, info2);
            flag1 = true;
      }
      catch (FormatException)
      {
            flag1 = double.TryParse(Value, NumberStyles.Any, info3, out Result);
      }
      catch (Exception)
      {
            flag1 = false;
      }
      return flag1;
       }

五、直接引用vb运行库(效率低)
    添加Visualbasic.runtime的引用
    代码中Using Microsoft.visualbasic;
    程序中用Information.isnumeric("ddddd");

[部分代码来自网络搜集未经调试, 通不过的...别怪我]

程序人生

c#字符串及数组操作

字符串操作(取当前时间)
string time=convert.tostring(DateTime.Today).split( new char []{‘ ‘});    textbox1.text=time[0]; 以空格作为分界点;
数组概述
C# 数组从零开始建立索引,即数组索引从零开始。C# 中数组的工作方式与在大多数其他流行语言中的工作方式类似。但还有一些差异应引起注意。
声明数组时,方括号 ([]) 必须跟在类型后面,而不是标识符后面。在 C# 中,将方括号放在标识符后是不合法的语法。
int[] table; // not int table[];
另一细节是,数组的大小不是其类型的一部分,而在 C 语言中它却是数组类型的一部分。这使您可以声明一个数组并向它分配 int 对象的任意数组,而不管数组长度如何。
int[] numbers; // declare numbers as an int array of any size
numbers = new int[10]; // numbers is a 10-element array
numbers = new int[20]; // now it’s a 20-element array
声明数组
C# 支持一维数组、多维数组(矩形数组)和数组的数组(交错的数组)。下面的示例展示如何声明不同类型的数组:
一维数组:int[] numbers;
多维数组:string[,] names;
数组的数组(交错的):byte[][] scores;
声明数组(如上所示)并不实际创建它们。在 C# 中,数组是对象(本教程稍后讨论),必须进行实例化。下面的示例展示如何创建数组:
一维数组:int[] numbers = new int[5];
多维数组:string[,] names = new string[5,4];
数组的数组(交错的):byte[][] scores = new byte[5][]; for (int x = 0; x < scores.Length; x++) {scores[x] = new byt[4];
}
还可以有更大的数组。例如,可以有三维的矩形数组:int[,,] buttons = new int[4,5,3];
甚至可以将矩形数组和交错数组混合使用。例如,下面的代码声明了类型为 int 的二维数组的三维数组的一维数组int[][,,][,] numbers; 
初始化数组
C# 通过将初始值括在大括号 ({}) 内为在声明时初始化数组提供了简单而直接了当的方法。下面的示例展示初始化不同类型的数组的各种方法。
注意 如果在声明时没有初始化数组,则数组成员将自动初始化为该数组类型的默认初始值。另外,如果将数组声明为某类型的字段,则当实例化该类型时它将被设置为默认值 null。
一维数组
int[] numbers = new int[5] {1, 2, 3, 4, 5};
string[] names = new string[3] {"Matt", "Joanne", "Robert"};
可省略数组的大小,如下所示:
int[] numbers = new int[] {1, 2, 3, 4, 5};
string[] names = new string[] {"Matt", "Joanne", "Robert"};
如果提供了初始值设定项,则还可以省略 new 运算符,如下所示:
int[] numbers = {1, 2, 3, 4, 5};
string[] names = {"Matt", "Joanne", "Robert"};
多维数组
int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[2, 2] { {"Mike","Amy"}, {"Mary","Albert"} };
可省略数组的大小,如下所示:
int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = new string[,] { {"Mike","Amy"}, {"Mary","Albert"} };
如果提供了初始值设定项,则还可以省略 new 运算符,如下所示:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Mike", "Amy"}, {"Mary", "Albert"} };
交错的数组(数组的数组)
可以像下例所示那样初始化交错的数组:
int[][] numbers = new int[2][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
可省略第一个数组的大小,如下所示:
int[][] numbers = new int[][] { new int[] {2,3,4}, new int[] {5,6,7,8,9} };-或-
int[][] numbers = { new int[] {2,3,4}, new int[] {5,6,7,8,9} };
请注意,对于交错数组的元素没有初始化语法。
访问数组成员
访问数组成员可以直接进行,类似于在 C/C++ 中访问数组成员。例如,下面的代码创建一个名为 numbers 的数组,然后向该数组的第五个元素赋以 5:
int[] numbers = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
numbers[4] = 5;
下面的代码声明一个多维数组,并向位于 [1, 1] 的成员赋以 5:
int[,] numbers = { {1, 2}, {3, 4}, {5, 6}, {7, 8}, {9, 10} };
numbers[1, 1] = 5;
下面声明一个一维交错数组,它包含两个元素。第一个元素是两个整数的数组,第二个元素是三个整数的数组:
int[][] numbers = new int[][] { new int[] {1, 2}, new int[] {3, 4, 5}};
下面的语句向第一个数组的第一个元素赋以 58,向第二个数组的第二个元素赋以 667:
numbers[0][0] = 58;
numbers[1][1] = 667;
数组是对象
在 C# 中,数组实际上是对象。System.Array 是所有数组类型的抽象基类型。可以使用 System.Array 具有的属性以及其他类成员。这种用法的一个示例是使用“长度”(Length) 属性获取数组的长度。下面的代码将 numbers 数组的长度(为 5)赋给名为 LengthOfNumbers 的变量:
int[] numbers = {1, 2, 3, 4, 5};
int LengthOfNumbers = numbers.Length;
System.Array 类提供许多有用的其他方法/属性,如用于排序、搜索和复制数组的方法。
对数组使用 foreach
C# 还提供 foreach 语句。该语句提供一种简单、明了的方法来循环访问数组的元素。例如,下面的代码创建一个名为 numbers 的数组,并用 foreach 语句循环访问该数组:
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers){System.Console.WriteLine(i);}
由于有了多维数组,可以使用相同方法来循环访问元素,例如:
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers){Console.Write("{0} ", i);}
该示例的输出为: 9 99 3 33 5 55
不过,由于有了多维数组,使用嵌套 for 循环将使您可以更好地控制数组元素