|
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 ; }
上一页 [1] [2] [3] 下一页
 【责编:Youping】 |