2011-07-20 218 views
-1

C#的新手,所以這只是我讀了一些tutiroals後猜測它。C#創建一個實例

我有一個類叫做PS3RemoteDevice:

namespace PS3_BluMote 
{ 
    public class PS3RemoteDevice 
    { 

而且從我的主要形式按鈕我嘗試這樣做:

PS3RemoteDevice PS3R = new PS3RemoteDevice; 
PS3R.Connect(); 

當然不過,似乎並沒有工作。因爲我是一個noob會有點幫助會很棒!

謝謝!

大衛

PS3RemoteDevice.cs代碼

using System; 
using System.Collections.Generic; 
using System.Timers; 
using HIDLibrary; 

namespace PS3_BluMote 
    { 
     public class PS3RemoteDevice 
     { 
     public event EventHandler<ButtonData> ButtonAction; 
     public event EventHandler<EventArgs> Connected; 
     public event EventHandler<EventArgs> Disconnected; 

     private HidDevice HidRemote; 
     private Timer TimerFindRemote; 
     private Timer TimerHibernation; 

     private int _vendorID = 0x054c; 
     private int _productID = 0x0306; 
     private int _batteryLife = 100; 
     private bool _hibernationEnabled = false; 


    public PS3RemoteDevice(int VendorID, int ProductID, bool HibernationEnabled) 
    { 
     if (HibernationEnabled) 
     { 
      TimerHibernation = new Timer(); 
      TimerHibernation.Interval = 60000; 
      TimerHibernation.Elapsed += new ElapsedEventHandler(TimerHibernation_Elapsed); 
     } 

     _vendorID = VendorID; 
     _productID = ProductID; 
     _hibernationEnabled = HibernationEnabled; 
    } 


    public void Connect() 
    { 
     if (!FindRemote()) 
     { 
      StartRemoteFindTimer(); 
     } 
    } 

等等等等....

+0

你在那裏有一些語法錯誤,那是你在說什麼?而不是我們猜測,你應該告訴我們錯誤。 –

+0

PS3RemoteDevice PS3R = new PS3RemoteDevice();代替? (是一個編譯錯誤)如果不是那麼真的不能幫助你,除非你向我們展示庫代碼或將我們鏈接到你使用的庫 –

+0

你缺少構造函數括號:'new PS3RemoteDevice();' – BrokenGlass

回答

1

你的類只有一個構造函數三個參數:

public PS3RemoteDevice(int VendorID, int ProductID, bool HibernationEnabled) 
{ ... } 

就像在任何其他方法調用當您使用new實例化一個對象時,您需要傳遞這些參數,例如:

int vendorId = 5; 
int productId = 42; 
PS3RemoteDevice PS3R = new PS3RemoteDevice(vendorId, productId, false); 
+0

DOH !!!!!我知道我忘記了一件簡單的事情!謝謝BrokenGlass! :o) – StealthRT

3

假設你擁有的類代碼的其餘部分,

PS3RemoteDevice PS3R = new PS3RemoteDevice();會的工作,與parantheses。

+0

我收到錯誤**錯誤'PS3_BluMote。PS3RemoteDevice'不包含一個構造函數,它接受'0'參數** – StealthRT

+0

好吧,如果您發佈了PS3RemoteDevice的其他類代碼,那麼我可以提供幫助。 –

+0

完成!看看OP:o) – StealthRT

3

嘗試

PS3RemoteDevice PS3R = new PS3RemoteDevice(); 

EDIT(使用參數):

PS3RemoteDevice PS3R = new PS3RemoteDevice(someVendorID, some ProductID, someBoolHibernationEnabled); 
+0

我得到的錯誤**錯誤'PS3_BluMote.PS3RemoteDevice'不包含一個構造函數,它需要'0'參數** – StealthRT

+0

然後您需要將參數放入paranthesis中...請參閱編輯。 – Yahia

+0

Doh!感謝您指出這一點,Yahia。 – StealthRT

1

當您創建對象的新實例時,您正在調用其構造函數方法(簡稱構造函數)。它就像任何其他方法一樣,但如果定義它,則需要您調用它。語法是new MyObject(... parameters here ...);

我通過您先前的問題進行搜索,發現a screenshot of the code you are using。你有一個帶參數的構造函數。這些參數沒有被定義爲可選的,所以你必須提供它們。這些是vendorId,productIdhibernationEnabled

所以你的代碼將是new PS3RemoteDevice(0x054c, 0x0306, false);。或者至少這就是截圖中默認值的樣子。通過閱讀您正在使用的代碼的文檔來找出正確的值。

+0

太棒了,謝謝你的幫助,Merlyn! :O) – StealthRT