C#相当于#define,其主体与c相同 [英] C#'s equivalent of #define with a body as in c
问题描述
您好,
我刚刚开始使用c#所以这个问题可能显得微不足道。但我找不到答案(我希望找到)
,因为我可以创建一个小的宏,例如打印常量的名称和值
Hello,
I'm just starting out with c# so the question may appear little trivial. But I couldn't find an answer (I wished to look for)
as in c I can create a small macro to e.g. print the name and value of a constant
#define print_it(x) printf("Name: %s, Value: %d", ##x, x)
如果我有一个符号如
and if I have a symbol like
#define CUBE_ARM_WIDTH 5
我会这样做
I'd do it like
print_it(CUBE_ARM_WIDTH);
我得到的输出为
and I'd get the output as
Name: CUBE_ARM_WIDTH, Value: 5
但我如何在c#中执行此操作,其中允许使用#define但不允许给它赋值或者像body这样的函数。 />
并且还假设我在两个不同的cs文件中使用常量值,例如
But how do I do it in c#, where #define is allowed but to give it a value or a function like body is not allowed.
and also suppose I am using a constant value in two different cs files, something like
#define GRID_ARRAY_WIDTH 20
我将它放在一个头文件中,将它包含在两个文件中并使用名称I #defined自由。但是在c#中也不能同样容易地做到这一点。
我知道我们可以使用枚举。但在这种情况下:
I'll put it in a header file, include it in both files and use the name I #defined freely. But the same can not be done in c# with the same ease.
I know we can use enums. but in that case:
class myShapes
{
enum GridParams
{
GridArrayWidth 20,
GridArrayHeight 20
};
}
我的名字已经有点长,变得更长即
my the name that was already a little long, becomes even longer i.e.
myShapes.GridParams.GridArrayWidth
#define它长16个字符,现在是34个字符。
我认为应该有一个更好的方法,显然,我没有遇到过。
那我怎么用C#做这些事情。
请不要我弄错了,我很钦佩C#一个简单的事实,即我在VC ++中可以用一些文件完成代码,可以用c#中的几行简单而直观地完成。
我只是想知道我是否可以使用我在使用C时学到的一些东西。
问候,
gdshukla
with #define it was 16 characters long and now it is 34 characters.
I think there should be a better way of doing it, which apparently, I have not come across.
So how do I do these things in C#.
Please don't get me wrong, I admire C# a lot for a simple fact that what I could do in VC++ with some files-full of code can be done in few lines in c# which are simple and very intuitive.
I just want to know if I can use some of the things I learned while using C.
Regards,
gdshukla
推荐答案
你可以为这些东西使用静态函数
You can use a static function for these things
namespace MyNamespace
{
public static class MyFunctions
{
public string DoSomething (string p)
{
return p.ToUpper();
}
}
}
然后使用
then to use
string x = MyNamespace.MyFunctions.DoSomething("hello");
C#做不有这种类型的任何宏预处理。
没有像宏#x
或a ## b
。
同样,由于没有替换过程,
#define CUBE_ARM_WIDTH 5
实际上没有意义。
所以,是的,有些东西在C#中比在C / C ++中更冗长。
我们大多数人都发现这些好处超过了额外的冗长。
C# does not have any macro preprocessing of this type.
There is nothing like macro#x
ora ## b
.
Likewise, since there is no substitution process,
#define CUBE_ARM_WIDTH 5
doesn't really make sense.
So, yes, some things are more verbose in C# than in C/C++.
Most of us have found that the benefits outweigh the extra verbosity.
这篇关于C#相当于#define,其主体与c相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!