无法访问静态 Class 函数?
Can Not Access Static Class Function?
这是我的代码
static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
class manageCAN
{
// Getting the String for .dll Address
string dllfile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\VTC1010_CAN_Bus.dll";
// Loading dll using Native Methods
IntPtr pDll = NativeMethods.LoadLibrary(dllfile);
}
我收到一个错误:错误 1 字段初始值设定项无法引用非静态字段、方法或 属性 'manageDLL.manageCAN.dllfile'
请提出解决方案。为什么我不能初始化我的变量 "pDll"?
Why can't I initialize my variable "pDll"?
编译器会告诉您确切原因 - 您无法访问实例字段初始值设定项中的实例字段。看起来这些应该是静态的:
static readonly string dllfile = ...;
static readonly IntPtr pDll = NativeMethods.LoadLibrary(dllfile);
但是如果你真的希望它们成为实例字段,你需要在构造函数中初始化pDll
:
class manageCAN
{
// Getting the String for .dll Address
string dllfile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\VTC1010_CAN_Bus.dll";
// Loading dll using Native Methods
IntPtr pDll;
public manageCAN()
{
pDll = NativeMethods.LoadLibrary(dllfile);
}
}
这是我的代码
static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
class manageCAN
{
// Getting the String for .dll Address
string dllfile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\VTC1010_CAN_Bus.dll";
// Loading dll using Native Methods
IntPtr pDll = NativeMethods.LoadLibrary(dllfile);
}
我收到一个错误:错误 1 字段初始值设定项无法引用非静态字段、方法或 属性 'manageDLL.manageCAN.dllfile'
请提出解决方案。为什么我不能初始化我的变量 "pDll"?
Why can't I initialize my variable "pDll"?
编译器会告诉您确切原因 - 您无法访问实例字段初始值设定项中的实例字段。看起来这些应该是静态的:
static readonly string dllfile = ...;
static readonly IntPtr pDll = NativeMethods.LoadLibrary(dllfile);
但是如果你真的希望它们成为实例字段,你需要在构造函数中初始化pDll
:
class manageCAN
{
// Getting the String for .dll Address
string dllfile = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\VTC1010_CAN_Bus.dll";
// Loading dll using Native Methods
IntPtr pDll;
public manageCAN()
{
pDll = NativeMethods.LoadLibrary(dllfile);
}
}