有关常数一般CS问题 [英] General CS question about constants

查看:138
本文介绍了有关常数一般CS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#编程,在编程C.后,所以我使用了很多常量,如DEFAULT_USER_ID,REMOTE_ADDRESS和这样的...

I'm programming using C#, after programming on C. So I'm using a lot of constants such as "DEFAULT_USER_ID", "REMOTE_ADDRESS" and such...

在我看来,这是很老土使用这样的常量,也许有使用对象之间的一些常量数据的其他更优雅的方式。

It seems to me that it's pretty "old fashioned" to use such constants and maybe there is some other more elegant way for using some constant data between objects.

关于如何可以这样优雅做任何想法?

Any ideas on how this could be done elegantly?

感谢。

推荐答案

使用的东西,像常量 DEFAULT_USER_ID 仍是要走的路(除非你希望它是可配置的,但那是另一个话题)。 - > 常量(C#参考)

Using constants for stuff like DEFAULT_USER_ID is still "the way to go" (unless you want it to be configurable, but that's another topic). --> const (C# Reference)

不要使用枚举常数( FILE_TYPE_DOC = 1 FILE_TYPE_XLS = 2 , ...)。这是可以做到更优雅的C#与枚举

Don't use constants for enumerations (FILE_TYPE_DOC = 1, FILE_TYPE_XLS = 2, ...). This can be done more elegantly in C# with enums:

enum FileType {
   Doc,
   Xls,   // or, optionally, "Xls = 2".
   ...
};

您也可以使用此为标志(常量由位运算符组合的),这是另一种常见的用例用C常数:

You can also use this for flags (constants combinable by bitwise operators), which is another common use case of constants in C:

[Flags]
enum FontDecoration {
    None = 0,
    Bold = 1,
    Italic = 2,
    Underline = 4
}

这篇关于有关常数一般CS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆