1 枚举定义:
enum BillStatus:int
{
AddNew = 1,
Audit = 2,
Delete = 3
}
把AddNew转化成对应int的方法:直接强制转型,int a= (int)BillStatus.AddNew。
也可以把string转换为枚举值,但其语法略复杂一些。有一个特定的命令用于这种类型的转换,即Enum.Parse(),使用方式:
(enumarationType)Enum.Parse(typeof(enumerdionType),enumerdionString);
使用了另一个运算符typeof可以得到操作数的类型。
例如:int a = (int)Enum.Parse(typeof(BillStatus),"AddNew");
MessageBox.Show(this,a.ToString());Enum工具类中有GetValues等操纵枚举的方法。例如:
String[] names = Enum.GetNames(typeof(BillStatus));
foreach(String s in names)
{
MessageBox.Show(this,s);}
实例:Object obj = some.a;
if(obj is Enum)
{
int
value = (int)obj;
Console.WriteLine(value);
Object en = Enum.Parse(obj.GetType(),value.ToString());
Console.WriteLine(en.GetType()+":"+en.ToString());
}
2 C#中基本类型也是类。比如:int a = (int)Enum.Parse(typeof(BillStatus),"AddNew");
MessageBox.Show(this,a.ToString());
3 委托
委托是一种可以把引用存储为函数的类型。 委托的声明常类似于函数,但不带函数体,且要使用delegate关键字。委托的声明指定了一个函数签名,其中包含一个返回类型和参数列表。在定义了委托后,就可以声明该委托类型的变量。接着切始化这个变量为与委托有相同签名的函数引川。之后,就可以便用委托变量调用这个函数。
delegate double processDelegate(double param1,double param2)
static double Multiply(double param1,double param2)
{
return param1*param2;
}
processDelegate aPro = new processDelegate(Multiply);
aPro(2,2);
C#中委托的机制和Delphi中的事件机制类似。例如myTimer+=new EclapsedEventHandler(doTimer);这样就为Timer的onTimer指定了处理函数。不同点在于可以通过myTimer+=的方式为事件指定多个处理函数,这一点又和java中事件列表类似。
自定义事件的实现:
定义一个名称为MessageHanler 的委托,然后
public event MessageHanler msgArrived;
想要
4、
Debug.writeLine()
Trace.writeLine()
Debug.Assert()
Trace. Assert ()
5、
在默认情况下,类声明为内部的,即只有当前工程中的代码才能访问它。可以用intemal访问修饰符关键字显式指定,但这是不必要的。
在类定义中指定继承。为此,要在类名的后面加上一个冒号,其后是基类名
域也可以他用关键字readonly,表示这个域只能在执行构造函数的过程中赋值.例如:public readonly int MyInt=17;
也可以在方法定义中使用下述关键字:virtual,override,abstract,extern。
如果使用了override,可以使用sealed指定在派生类中不能重写此方法。public override sealed void DoSome ()
如果确实要隐藏该成员,就可以使用new关键字显式地说明,这是我们要隐藏的成员:
new public void DoIt()
.NET中的大多数控件都派生于System.Windows.Forms.Contro类。
6 C#支持运算符重载,语法和C++的一样。
7 C# 支持is as运算符,和Delphi类似。
8 System.Exception
9 if(dlg.ShowDialog()==DialogResult.OK)
10 读取文本文件的方法:
using(StreamReader reader=File.OpenText(filaName))
{
text.Text = reader.ReadToEnd();
}
11 SaveFiIeDialog的AddExtension是一个布尔属性,它定义了文件扩展名是否应白动添加到用户输入的文件名,它使用DefaultExt作为默认扩展名。
12 数据库操作:
(1) this.oleDbDataAdapter1.Fill(this.dataSet11,0,0,"T_Agentist");
(2) this.BindingContext[this.dataSet11,"T_Agentist"].Position++;
(3) oleDbConnection1.Open();
OleDbCommand command = this.oleDbConnection1.CreateCommand();
command.CommandText = "select * from T_Agentist";
OleDbDataReader reader = command.ExecuteReader();
while(reader.Read())
{
MessageBox.Show(this,reader["Name"].ToString());
}
reader.Close();oleDbConnection1.Close();
13 在使用adapter的update方法的时候,如果报错,有可能是Dataset对应的表没有定义主键的原因,导致生成的UpdateCommand和InsertCommand错误。只要在adapter上点击右键,选择“配置适配器”即可。
14 代码实现update的方法:OleDbDataAdapter adapter = new OleDbDataAdapter("select * from T_Agentist",this.oleDbConnection1);
new OleDbCommandBuilder(adapter);
DataSet dataset = new DataSet();
adapter.Fill(dataset,"T_Agentist");
dataset.Tables["T_Agentist"].Rows[0]["Name"] = "tom";
adapter.Update(dataset,"T_Agentist");
注意,必须有这一步:new OleDbCommandBuilder(adapter);否则在update的时候回出问题。
Update的实现原理:将所有已修改的字段拼成update语句,其中的where子句为所有字段的and。在执行update之前先用where子句为所有字段的and的select语句查询一下有几条,如果有非一条,则报错,否则执行update。
DataSet 是数据在内存中的一个镜像。
Dataset包含一组相关的DataTable对象,代表要使用的数据库表。每一个DataTable对象都有子DataRow和DataColumn对象。在使用Dataset之前,我们必须使用来日数据库的数据填允它。可以使用DntaAdapter中的Fill()方法来完成这种工作。fill()传递的第一个参数是希望用来填充对象的数据组,第二个参数是Dataset中的DataTable的名称。
DataTable customerTable = thisDataSet.Tables["customers"];
DataRow row = customerTable.Rows[9];
Object comName = row["FName"];
15 为DataSet设定主键:
DataColumn[] keys=new DataColumn[1];
keys[0] = dataSet.Tables["Customers"].Columns["customerId"];
dataSet.Tables["Customers"].PrimaryKey = keys;
这样设定以后就可以通过find方法来根据主键来查询指定记录了:
DataRow findRow = dataSet.Tables["Customers"].Rows.Find("001");
另一种办法是从数据库中加载主键码,这不合默认完成。但是,您可以显式地告诉AD0.NET加载主键玛的信息,方法是在填充Dataset之前设置DataAdapter MissingSchemaAction属性。
如:
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(dataset,"T_Agentist");
16 MessageBox.Show(this,new OleDbCommandBuilder(adapter).GetInsertCommand().CommandText);
17 如果希望从Dabset的Rows集合中,而不是从数据库删除一列的话,只要在update之前调用acceptChanges方法既可。
18 直接执行sql语句的方法:
OleDbCommand cmd = new OleDbCommand("update T_Agentist set Name=Name+'cust'",this.oleDbConnection1);
try
{
oleDbConnection1.Open();
cmd.ExecuteNonQuery();
}catch(Exception ex)
{
MessageBox.Show(this, ex.Message);
}
19 (1)File.Create("c:/ccc.cc");
(2)System.Diagnostics.Process.Start("notepad.exe");
(4) 截获消息队列
public Boolean PreFilterMessage(ref System.Windows.Forms.Message msg){
Console.WriteLine(msg.ToString());
return
false;}
Application.AddMessageFilter(this);
20 C#中基类的标识符是base。
21
(1)File、Directory类和FileInfo,DirectoryInfo类的不同在于File、Directory全是静态方法,而FileInfo,DirectoryInfo则代表一个文件或目录对象。
(2)FileStream StreamWriter
(3)Decoder d = System.Text.Encoding.UTF8.GetDecoder();
d.GetChars(byData,0,byData.Lenghth,charData,0);
22 C#解决方案中的Assamble.cs是设置工程的公司、版本等信息用的。
23 在定义类的时候只要在头部加上[Serializable]就标识此类可以序列化。默认所有此类的字段都将序列化,如果想明确表示某个字段无需序列化,只要在字段上方标识[NoSerializable]即可。
类序列化的例子。
Stream stream = File.Open("demo.dat",FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, new Person());
stream.Close();
反序列化:
Stream stream = File.Open("demo.dat",FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(stream);
Person p = 0bj as Person;
stream.Close();
24 .Net类库部分内容:
(1)System.Array。
(2)int lhs = System.Int32.Parse(lhsOperand.Text);
(3)System.Convert工具类有很多在DateTime,int,String等类型之间转换
(5) System.DateTime。
(6) System.DateOfWeek定义了周各天的枚举。
(7) System.DBNull
(8) System.Environment工具类有如下几个重要方法
public static string[] GetCommandLineArgs ( ) 返回包含当前进程的命令行参数的字符串数组。
public static System.String
GetEnvironmentVariable ( System.String
[i]variable[/i] ) 返回指定环境变量的值。
public static System.Collections.IDictionary
GetEnvironmentVariables ( )
public static string[] GetLogicalDrives ( ) 返回包含当前计算机中的逻辑驱动器名称的字符串数组。
CurrentDirectory
public static string NewLine
获取为此环境定义的换行字符串。
public static System.String
GetFolderPath ( System.Environment.SpecialFolder
[i]folder[/i] ) 获取指向由指定枚举标识的系统特殊文件夹的路径。 其中System.Environment.SpecialFolder是表示文件夹类型的枚举。
public static System.OperatingSystem OSVersion获取包含当前平台标识符和版本号的 System.OperatingSystem 对象。
public static int TickCount获取系统启动后经过的毫秒数。
(9) System.Guid 有NewGuid等方法。
(10) System.Icloneable、System.Icomparable、System.Iconvertible、System.IFormatProvider 、System.IFormattable
(11) System.MarshalByRefObject允许在支持远程处理的应用程序中跨应用程序域边界访问对象。
(12) System.Math含有一些常用数学函数
(13) System.Collections.ArrayList、System.Collections.BitArray、System.Collections.CollectionBase、System.Collections.DictionaryBase、System.Collections.Hashtable、System.Collections.Queue、System.Collections.SortedList、System.Collections.Stack
(14) System.Collections.Icollection、System.Collections.Icomparer、System.Collections.Idictionary、System.Collections.IdictionaryEnumerator、System.Collections.Ienumerable、System.Collections.Ienumerator、System.Collections.Ilist、
(15) System.IO.MemoryStream(无论是System.IO.MemoryStream还是System.IO.FileStream,都是继承的System.IO.Stream)
(16) System.Resources包中是读取资源文件用的类。System.Security.Cryptography包中含有一些常用的加密算法和一些签名算法。
(17) System.Text中含有编码转换相关的类。System.Text.StringBuilder相当于java中的StringBuffer
(18) System.Threading.Monitor提供同步对对象的访问的机制。 System.Threading.Mutex同步基元也可用于进程间同步。 System.Threading.Thread创建并控制线程,设置其优先级并获取其状态。
System.Threading.ThreadPool提供一个线程池,该线程池可用于发送工作项、处理异步 I/O、代表其他线程等待以及处理计时器。
System.Threading.Timer提供以指定的时间间隔执行方法的机制。无法继承此类。
(19) System.Configuration包中是操纵.config用的类。System.Configuration.AppSettingsReader、System.Configuration.ConfigXmlDocument等。
(20) System.Net包中是常用的网络类。如System.Net.Cookie、System.Net.Dns、System.Net.IPAddress、System.Net.WebClient、 System.Net.WebProxy、System.Net.Sockets.Socket、System.Net.Sockets.TcpClient、System.Net.Sockets.TcpListener、System.Net.Sockets.UdpClient
(21) System.Windows.Forms.Application。
public static void AddMessageFilter ( System.Windows.Forms.IMessageFilter
[i]value[/i] )
添加消息筛选器以便在向目标传送 Windows 消息时监视这些消息。
public static void DoEvents ( )
处理当前在消息队列中的所有 Windows 消息。
public static void EnableVisualStyles ( )
启用应用程序的 Windows XP 可视化样式。
public static void Exit ( )
public static System.Threading.ApartmentState
OleRequired ( )
初始化当前线程上的 OLE。
(22) System.Windows.Forms.ApplicationContext
public System.Windows.Forms.Form MainForm [ get, set ]
(23) System.Windows.Forms.AxHost 包装 ActiveX 控件,并将其作为功能完全的 Windows 窗体控件进行公开。
(24) System.Windows.Forms.PropertyGrid
system.xml
25 ui控件的验证。只要设定ui控件的[i]CausesValidation[/i][i]属性为true,这样在失去焦点的时候就会触发[/i][i]Validating[/i] and [i]Validated[/i][i]事件。[/i]
[i]26 属性:[/i]
(1)属性也是一个类。
Assembly ass = Assembly.LoadFile(openFileDialog1.FileName);
object[] atts = ass.GetCustomAttributes(true);
(2)简单的自定义属性:
namespace WindowsApplication9{
[AttributeUsage(AttributeTargets.Field,AllowMultiple=true)]public
class TableAttribute:Attribute
{public
readonly String tableName;
public
readonly String fieldName;
public TableAttribute(String tableName,String fieldName){
this.tableName = tableName;this.fieldName = fieldName;}
}
}
namespace WindowsApplication9{
publicclass PersonInfo{
[Table("T_Person","FName")]
public String name;
[Table("T_Person","FAge")]public
int age;}
}
调用MemberInfo[] infos = typeof(PersonInfo).GetMembers();
foreach(MemberInfo method in infos)
{
object[] atts = method.GetCustomAttributes(typeof(TableAttribute),false);
foreach(Object obj in atts){
TableAttribute ta = (TableAttribute)obj;
Console.WriteLine("tableName:"+ta.tableName+" fieldname:"+ta.fieldName);
}
}
27 (1)HttpCookie obj = HttpContext.Current.Request.Cookies["read"];
this.HyperLink1.Text = obj == null?null:obj.Value.ToString();
(2)HttpCookie c = new HttpCookie("read");
c.Value = true.ToString();HttpContext.Current.Response.Cookies.Add(c);
(3)Response.Redirect("WebFormAbout.aspx");
(4)webservice :
Service1 a = new Service1();
this.Button3.Text = a.SayHello(Button3.Text);
28 Web页面上DataGrid绑定的方法,在onload中:
Page.DataBind();
this.oleDbDataAdapter1.Fill(this.dataSetOrder1);
this.DataGrid1.DataBind();
29 new WebClient().DownloadFile(TextBoxUrl.Text,"c:/temp/c.dat");
30 Remoting使用:
中间层:
public interface IMan
{
String SayHello();
int CalcAdd(int n1,int n2);}
public
class Man:MarshalByRefObject,IMan{
public String SayHello()
{
return "你好!";}
public
int CalcAdd(int n1, int n2)
{
return n1+n2;
}}
服务器:ChannelServices.RegisterChannel(new HttpServerChannel(9999));
RemotingConfiguration.RegisterWellKnownServiceType(typeof(Man),"Man",WellKnownObjectMode.SingleCall);
客户端:
ChannelServices.RegisterChannel(new HttpClientChannel());
IMan man = (IMan)Activator.GetObject(typeof(IMan),"http://localhost:9999/Man");
MessageBox.Show(man.SayHello());
MessageBox.Show(man.CalcAdd(2,4).ToString());
最好三者放到同一个解决方案中,把中间层做成一个dll,供c s调用。
31 System.Runtime.Remoting.Messaging.CallContext可以在Remoting中为客户端线程保存状态数据。
32 写入windows事件日志:EventLog e = new EventLog();
e.Log = "测试!!!!!";
e.BeginInit();e.Source = "test";
e.WriteEntry("测试!!!!!!!!");
33 WebForm中加入控件的方法:如果向table单元格中拖入控件不能正常托放。需要在面板上按住托放就可以。
34 webform中datagrid模板列的使用,例如显示图片:
<asp:TemplateColumn><ItemTemplate>
<a href ='<%# "ShowUserFacePic.aspx?UserId="+(DataBinder.Eval(Container.DataItem, "FAuthorId")) %>'><asp:Image Runat=server ID="Image1" Width="150" Height="125"
ImageUrl='<%# "ShowUserFacePic.aspx?UserId="+(DataBinder.Eval(Container.DataItem, "FAuthorId")) %>' />
</a>
</ItemTemplate>
</asp:TemplateColumn>
35 C#提供了checked和unchecked运算符,如果把一个代码段标记为checked,则会执行溢出检查,如果发生溢出,则会抛出异常。用/checked选项进行编译,就可以检查程序中所有的溢出。
转载 如鹏网