C# create an instance of
本文关键字:of instance an create | 更新日期: 2023-09-27 18:02:30
c#新手,所以这只是我在阅读了一些教程后的猜测。
我有一个类叫做PS3RemoteDevice:
namespace PS3_BluMote
{
public class PS3RemoteDevice
{
从我的主表单按钮,我试着这样做:
PS3RemoteDevice PS3R = new PS3RemoteDevice;
PS3R.Connect();
当然,这似乎不起作用。我是个新手,如果能帮点忙就太好了!
谢谢!
大卫<
PS3RemoteDevice.cs代码/strong>
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();
}
}
等等…
假设您有剩下的类代码,
PS3RemoteDevice PS3R = new PS3RemoteDevice();
也可以,加上括号
try
PS3RemoteDevice PS3R = new PS3RemoteDevice();
编辑(带参数):
PS3RemoteDevice PS3R = new PS3RemoteDevice(someVendorID, some ProductID, someBoolHibernationEnabled);
你的类只有一个带三个参数的构造函数:
public PS3RemoteDevice(int VendorID, int ProductID, bool HibernationEnabled)
{ ... }
就像在任何其他方法调用中一样,当您使用new
实例化对象时需要传递这些参数,例如:
int vendorId = 5;
int productId = 42;
PS3RemoteDevice PS3R = new PS3RemoteDevice(vendorId, productId, false);
当您创建对象的新实例时,您正在调用其构造函数方法(简称构造函数)。它与任何其他方法一样,但是如果定义了它,则需要调用它。语法为new MyObject(... parameters here ...);
。
我通过你以前的问题搜索,发现你正在使用的代码的屏幕截图。你有一个接受参数的构造函数。这些参数没有定义为可选的,因此必须提供它们。这些是vendorId
, productId
和hibernationEnabled
。
所以你的代码是new PS3RemoteDevice(0x054c, 0x0306, false);
。或者至少截图中的默认值是这样的。通过阅读你正在使用的代码的文档,找出传递的正确值。