c# - C# 是否具有与#def 常量等效的#include?

标签 c# c

在人们拆开这个问题之前,我会解释一下我想做什么。

我目前有一个可以访问共享内存的 C 程序。 C 程序通过#defined 偏移量导航此共享内存。示例:

#define VAR_1 0x2000

现在我有一个 C# 程序可以显示共享内存中的数据。我正在尝试确定如何使用我的 C 程序使用的 #defines 并让我的 C# 程序也引用它们。

我试图避免维护包含这些定义的两个文件。

因此,C# 程序是否可以使用 .h 文件中的#defines?

谢谢,

最佳答案

The short answer is no :

The #define directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.

你可以这样做:

常量.cs:

#if __STDC__
#define public
#else
namespace foo
{
    class Constants {
#endif

public const int VAR_1 = 0x2000;

#if __STDC__
#undef public
#else
    }
}
#endif

主.c:

#include <stdio.h>
#include "constants.cs"

int main(void)
{
    printf("%d\n", VAR_1);
    return 0;
}

程序.cs:

using System;
namespace foo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Constants.VAR_1);
        }
    }
}

这导致:

$ gcc -Wall -Wpedantic main.c && ./a.out 
8192
$ dotnet run
8192

这是在 C 中使用 const int 而不是 #define,但这可能是您愿意做出的权衡。

关于c# - C# 是否具有与#def 常量等效的#include?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46198618/

相关文章:

c - 使用 gcc -c 生成 .o 文件

c - Do while 循环给出意外的输出

C 检查 2D-Int 数组何时已满

c# - 如何在 C# 中声明一个自由长度的二维数组

c# - WPF 有条件地启用键绑定(bind)

c# - 返回值是 IEnumerable 而不是 IPaged

c# - 什么时候单个语句需要花括号?

C 套接字 : Comparison between pointer and integer terminal error

c++ - 在 C/C++ 中将天文数字大的数字转换为人类可读的形式

c# - 哪种方法重载可以从 VBScript 访问?