C#類庫編譯兩步走
- usingSystem;
- namespaceconn
- {
- publicclassLogin
- {
- //在此類中定義一個靜態(tài)的字段(屬性),
- 返回一個字符串
- publicstaticstringConnection
- {
- get{return@"Server=database_servername;
- DataBase=Northwind;userid=sa;
- password=yourpassword;";}
- }
- //注意@不可以少!
- }
- }
此時需要在DataReaderSql使用到類login中的字段Connection(下面代碼第9行)
DataReaderSql.cs
- 1 using System;
- 2 using System.Data.SqlClient;
- 3
- 4
- 5 public class DataReaderSql
- 6 {
- 7 public static int Main(
- string[] args)
- 8 {
- 9 string source = Login.Connection ;
- 10 string select = "
- SELECT ContactName,CompanyName FROM Customers" ;
- 11
- 12 SqlConnection conn =
- new SqlConnection ( source ) ;
- 13
- 14 try
- 15 {
- 16 using ( conn )
- 17 {
- 18 conn.Open ( ) ;
- 19
- 20 SqlCommand cmd = new SqlCommand
- ( select , conn ) ;
- 21
- 22 using ( SqlDataReader aReader =
- cmd.ExecuteReader ( ) )
- 23 {
- 24 while ( aReader.Read ( ) )
- 25 Console.WriteLine ( "'{0}'
- from {1}" , aReader.GetString(0) ,
- aReader.GetString ( 1 ) ) ;
- 26
- 27 aReader.Close ( ) ;
- 28 }
- 29
- 30 conn.Close ( ) ;
- 31 }
- 32 }
- 33 catch ( Exception e )
- 34 {
- 35 Console.WriteLine ( e ) ;
- 36 Console.WriteLine ( ) ;
- 37 Console.WriteLine ( "
- Chances are your database does
- not have a user" ) ;
- 38 Console.WriteLine ( "
- called QSUser, or you do not have
- the NetSDK database installed." ) ;
- 39 }
- 40
- 41 return 0;
- 42 }
- 43 }
也就是說目前我們需要解決的問題是如何在C#類庫編譯的時候可以及時的讓程序可以知道Login.Connection在哪里。
那么我們應(yīng)該怎么做才能實現(xiàn)C#類庫編譯呢?
在這里我們不依靠namespace我們使用動態(tài)鏈接庫。
C#類庫編譯分2步:
一、使用命令csc/t:librarylogin.cs編譯得到login.dll
二、使用命令cscDataReaderSql.cs/r:login.dll編譯并指向login.dll動態(tài)鏈接庫文件得到DataReaderSql.exe
希望對剛開始學(xué)C#的并打算繼續(xù)打好基礎(chǔ)的人有所幫助!
【編輯推薦】