简体   繁体   English

何处将常量放在WCF项目中

[英]Where to place constants in a WCF project

I am new to WCF, Where do I place the constants for my project? 我是WCF的新手,我在哪里为项目放置常量?

I generally create a file with a namespace that holds all my static constants. 我通常创建一个文件夹,其中包含一个包含所有静态常量的命名空间。 But we cannot have static variables in WCF if the service is per-call or per-session. 但是,如果服务是每次调用或每次会话,我们就不能在WCF中拥有静态变量。 I don't want magic numbers in my code, I want constants that can be shared through out the project. 我不想在我的代码中使用魔术数字,我想要可以在整个项目中共享的常量。

Thanks 谢谢

If they are really constants, you would just put them in the relevant files with const keyword. 如果它们确实是常量,那么您只需将它们放在带有const关键字的相关文件中即可。 Constants cannot be changed thefore they are thread safe. 常量在线程安全之前无法更改。

If you need to change the value of a variable, then it's not a constant and you need to think who can change it. 如果您需要更改变量的值,那么它不是常量,您需要考虑谁可以更改它。 If it is a user's responsibility, then you can put variables in a .config file and read them from there. 如果是用户的责任,那么您可以将变量放在.config文件中并从那里读取它们。 If code needs to change the variables, then you can use some locking mechanism to read/modify the values (lock, ReadWriteLock, etc). 如果代码需要更改变量,那么您可以使用一些锁定机制来读取/修改值(lock,ReadWriteLock等)。

The problem with using const or even classes which wrap magic numbers is that they can't be changed without re-compiling . 使用包含魔术数字的const或偶数类的问题是, 如果不重新编译它们就无法更改 You want to use a settings file. 您想使用设置文件。 These aren't very intuitive to set up, so follow these steps. 这些设置不是很直观,因此请按照以下步骤操作。 Right-click your project and choose Properties . 右键单击您的项目,然后选择“ 属性” Then find the Settings tab: 然后找到“ 设置”标签:

在此输入图像描述

Click the hyperlink which will create a Settings.settings file in your project. 单击将在项目中创建Settings.settings文件的超链接。 You can then edit the values in the designer: 然后,您可以在设计器中编辑值:

在此输入图像描述

Values are stored in your app.config or web.config (in your case, since it's a WCF project). 值存储在app.configweb.config (在您的情况下,因为它是WCF项目)。

A Simple static Class with static read only properties should work. 具有静态只读属性的简单静态类应该有效。

Public static class Foo
{
    public static int Bar { get { return 1337; }}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM