开发——硬编码

本文介绍了在软件开发中如何使用硬编码与配置文件来管理常量和设置。通过使用静态类中的常量或配置文件,可以有效地组织和管理应用程序中的固定值。文章提供了具体的代码示例,并解释了每种方法的适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可变变量的硬编码

 

 

声明static类赋值,或者添加config文件

You can use .config files or use constant values in a static class. If you don't need to change the values, I would suggest using constant values.

Example using constant values:

For example:

 

public static class Roles
{
  public const string Customer = "Customer";
  public const string Branch = "Branch";
} 

 

Usage:

 

if (role == Roles.Customer)
{

}
else if (role == Roles.Branch)
{

}

  

Example using config file:

    • Add a reference to System.Configuration
    • Add an "Application Configuration File" to your project
    • Add a configuration key to the configuration file like:
      <?xmlversion="1.0"encoding="utf-8"
      ?>
      <
      configuration
      >
         <
      appSettings
      >
            <
      addkey="myConfiguration"value="TestValue"
      />
         </
      appSettings
      >
      </
      configuration
      >
    • Within the code you can refer to the config file by using:
      string configValue = System.Configuration.ConfigurationManager.AppSettings["myConfiguration"];

 

 

使用枚举类

use an enum to help with readability.

enum MyTypes
{
 URL = 1,
 UserName = 2,
 Id = 3,
}

switch (myType)
{
    case MyTypes.URL:
        TidyUrl();
    case MyTypes.UserName:
        TidyUsername();
    case MyTypes.Id:
        TidyID();
    default:
        break;
}

  

转载于:https://www.cnblogs.com/panpanwelcome/p/7356736.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值