我在Mono上使用Libbcm2835.Net库@https://github.com/frankhommers/LibBcm2835.Net。我需要调用该库给出了Bcm2835类的方法:如何在不使用构造函数的情况下在C#中的另一个类中使用类的方法
using System;
using System.Runtime.InteropServices;
namespace LibBcm2835.Net
{
public sealed partial class Bcm2835
{
//please note: I added the constructor below and tried to use it to
//instantiate the object to be used in ADS1256.cs, but to no avail. I tried:
// Bcm2835 bcm2835 = new Bcm2835(1); And then invoking methods from bcm2835.
//But that gives me "An object reference is needed to access the non-static
//member ADS1256.bcm2835"
public Bcm2835(int a) { }
....all the methods here-on being non-static...
}
}
`
我现在想在另一个类ADS1256.cs如下使用此:
using System;
using LibBcm2835.Net;
namespace ForceSeer2
{
public class ADS1256
{
public ADS1256()
{
}
static Bcm2835 instance;
public static Bcm2835 Instance {
get { return instance;}
}
//example of a method in this class that uses a method from the class
//Bcm2835:
public static int initializeSPI()
{
//if i had done Bcm2835 bcm2835 = new Bcm2835(1); at the top,
//i would now do : if (bcm2835.bcm2835_init()==0) instead of
//the upcoming line, leading then to the error: "An object
//reference is needed to access the non-static
//member ADS1256.bcm2835"
if (Instance.bcm2835_init()==0)
return -1;
else {
Instance.bcm2835_spi_begin();
Instance.bcm2835_spi_setBitOrder ((byte)Bcm2835.bcm2835SPIBitOrder.BCM2835_SPI_BIT_ORDER_LSBFIRST);
Instance.bcm2835_spi_setDataMode ((byte)Bcm2835.bcm2835SPIMode.BCM2835_SPI_MODE1); //whats this about??
Instance.bcm2835_spi_setClockDivider ((ushort)Bcm2835.bcm2835SPIClockDivider.BCM2835_SPI_CLOCK_DIVIDER_256);//whats this about??
Instance.bcm2835_gpio_fsel ((byte)SPICS, (byte)Bcm2835.bcm2835FunctionSelect.BCM2835_GPIO_FSEL_OUTP);//whats this about??
Instance.bcm2835_gpio_set ((byte)SPICS);//sets SPICS to HIGH
Instance.bcm2835_gpio_fsel ((byte)DRDY, (byte)Bcm2835.bcm2835FunctionSelect.BCM2835_GPIO_FSEL_INPT);//whats this about??
Instance.bcm2835_gpio_set_pud ((byte)DRDY, (byte)Bcm2835.bcm2835PUDControl.BCM2835_GPIO_PUD_UP); //whats this about??
return 1;
}
}
这种使用给我的NullReferencePointer异常在线:
if (Instance.bcm2835_init()==0)
是什么原因造成的?我该如何纠正它?
您希望使用和不活动对象对其进行初始化。为什么?什么阻止你使用类的构造函数来创建它的一个对象? –
@ChetanRanpariya事实上,那里没有构造函数。我插入它并试图打电话给它。然而,它给出了同样的例外 –
_“实际上那里没有构造函数”__ - 你在说什么?你发布的代码显示了一个构造函数。你只需要传递一个'int'值给它。坦率地说,你的问题没有意义......要调用非静态方法,你必须创建一个实例。所以,**创建一个实例**。如果这不起作用,你需要更好地解释为什么不。 –