ClassInterfaceType.None表示沒有為該類生成類接口,如果沒有明確地實現接口,類只能通過IDispatch提供後期綁定訪問。用戶希望通過明確地由類實現的接口使外部對象能夠訪問類的功能,這也是推薦的ClassInterfaceAttribute的設置。
ComSourceInterfaces(typeof(DBCOM_Events))]確定許多作為COM事件向外部對象提供的接口。在本文的例子中,我們不對外部對象開放任何事件。
下面是COM對象完整的源代碼:
using System;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Data.SqlClIEnt;
using System.Windows.Forms ;
namespace Database_COMObject
{
[Guid(";694C1820-04B6-4988-928F-FD858B95C880";)]
public interface DBCOM_Interface
{
[DispId(1)]
void Init(string userid , string passWord);
[DispId(2)]
bool ExecuteSelectCommand(string selCommand);
[DispId(3)]
bool NextRow();
[DispId(4)]
void ExecuteNonSelectCommand(string insCommand);
[DispId(5)]
string GetColumnData(int pos);
}
// 事件接口Database_COMObjectEvents
[Guid(";47C976E0-C208-4740-AC42-41212D3C34F0";),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface DBCOM_Events
{
}
[Guid(";9E5E5FB2-219D-4ee7-AB27-E4DBED8E123E";),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(DBCOM_Events))]
public class DBCOM_Class : DBCOM_Interface
{
private SqlConnection myConnection = null ;
SqlDataReader myReader = null ;
public DBCOM_Class()
{
}
public void Init(string userid , string passWord)
{
try
{
string myConnectString = ";user id=";+userid+";;password=";+passWord+
";;Database=NorthWind;Server=SKYWALKER;Connect Timeout=30";;
myConnection = new SqlConnection(myConnectString);
myConnection.Open();
MessageBox.Show(";CONNECTED";);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
public bool ExecuteSelectCommand(string selCommand)
{
if ( myReader != null )
myReader.Close() ;
SqlCommand myCommand = new SqlCommand(selCommand);
myCommand.Connection = myConnection;
myCommand.ExecuteNonQuery();
myReader = myCommand.ExecuteReader();
return true ;
}
public bool NextRow()
{
if ( ! myReader.Read() )
{
myReader.Close();
return false ;
}
return true ;
}
public string GetColumnData(int pos)
{
Object obj = myReader.GetValue(pos);
if ( obj == null ) return ";"; ;
return obj.ToString() ;
}
public void ExecuteNonSelectCommand(string insCommand)
{
SqlCommand myCommand = new SqlCommand(insCommand , myConnection);
int retRows = myCommand.ExecuteNonQuery();
}
}
}