c# - 不调用静态构造函数

标签 c#

<分区>

我有以下类(class):

 private static class NativeSomeWrapper
   {
       [DllImport(NativeMethods.myCeeLib, EntryPoint = "Get_300_bars",
           CallingConvention = CallingConvention.Cdecl)]
       [return: MarshalAs(UnmanagedType.SysInt)]
       internal static extern IntPtr Get300bars([MarshalAs(UnmanagedType.SysInt)] IntPtr assessment);
   }

我有一个负责初始化 dll 的静态类:

internal static class NativeMethods
{
    public const string myCeeLib= "myCeeLib.dll";


    static NativeMethods()
    {
        var path = GetPathToMyCeeLibFile();
        var err = SetPath(path);
        if (err != ErrorCode.Ok)
        {
            throw new FileNotFoundException("Coulnt find myCeeLib file.");
        }
    }
}

问题是 NativeMethods 构造函数没有按预期被调用。

如何确保 NativeMethods 静态构造函数被调用并且库文件的路径设置正确?

最佳答案

编译器将在编译时计算该属性的值,因此在您执行程序时静态构造函数不会运行,因为在应用程序启动时em> 值已经被计算出来,你不需要访问类来获取它(从而触发静态构造函数)。

关于c# - 不调用静态构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38446070/

相关文章:

c# - 带有 .Net Core 2.1 的 HttpClient 挂起

c# - 尝试使用 Exchange Web 服务获取电子邮件时出现 ServiceObjectPropertyException?

c# - GDI+ 中发生一般性错误。 (仅当我在服务器上尝试时)

c# - 将单元测试写入程序集或单独的程序集中?

c# 9.0 记录 - 反射和泛型约束

c# - 为 List<T>() 提供大小参数

c# - 在 C# 中使用 "as"是一种安全的转换方式吗?

c# - 如何将 0 和 1 的字符串转换为 bool 数组

c# - 在单线程应用程序中调用 WMI 函数时的 DisconnectedContext MDA

c# - 服务器/客户端未发送所有字节(TCP 套接字)