C#的编码规范详细说明

时间:2022-01-13 10:07:43 

首先我们要明白一下几点,
1.代码写出来除了让他跑起来还有个非常非常重要的作用是维护,因为没有一成不变的代码,需求变化代码就不可避免的要变化。
2.你不是一个人在写代码,你身后有一个团队,这个团队中任何一个人都有可能会改你的代码,你如果写的不规范,后面的人会跟着写。举一个例子,最初的代码可能是这样的,


if (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-SP")
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    regetFlightInitData.TicketType = "0001";
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }
                else
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e.CostRate1 = 1.0M;
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }


但是过一时间又来个需求,对于“MU-WS”也需要走上面的逻辑,你会怎么写,如果你只是完成任务可能会像下面这样写


if (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-SP" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS")
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    regetFlightInitData.TicketType = "0001";
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }
                else
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e.CostRate1 = 1.0M;
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }


如果真的这么写你就是始作俑者,后面的人如果都和你一样就都会朝着葫芦画瓢,最后代码可能会是这样的


if (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-SP" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-SP" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-WS" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "XT-WS")
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    regetFlightInitData.TicketType = "0001";
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }
                else
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e.CostRate1 = 1.0M;
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }


看到效果了么,你需要脱一下下面的那个长条才能看到全部代码,这就是你的“因”种下后得到的果实。所以我们需要改进,常见的改进是回车换行,保证所有的代码都在你一眼能够看到的范围之内。改进后代码如下:


if (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-SP" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-SP" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-WS" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "XT-WS")
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    regetFlightInitData.TicketType = "0001";
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }
                else
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e.CostRate1 = 1.0M;
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;


是不是清爽一点,好看一点,如果你在第一次修改代码的时候这样写后面的人就会跟着这样写,他们可能会想,前面一个人这样写这样写应该不会有问题,虽然代码看起来有点别扭,这时候我们可以带着鉴赏的眼光看这段代码,如果再想一想还有更好的方法,为何不用switch呢?


switch (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper())
                {
                    case "CZ-SP":
                    case "MU-SP":
                    case "XT-WS":
                        {
                            OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                            e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                            e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                            e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                            regetFlightInitData.HighCostAndWeightEntity = e;
                            regetFlightInitData.TicketType = "0001";
                            //如果是海航,则不需要政策倒查验证
                            regetFlightInitData.ReSearchNoFlight = false;
                            break;
                        }
                    default:
                        {
                            OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                            e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                            e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                            e.CostRate1 = 1.0M;
                            regetFlightInitData.HighCostAndWeightEntity = e;
                            //如果是海航,则不需要政策倒查验证
                            regetFlightInitData.ReSearchNoFlight = false;
                            break;
                        }
                }


是不是更加简单,如果你这样写,后面的人会毫不犹豫地在后面加一个case “”:因为这个是大家再熟悉不过的语法了,丝毫不用怀疑这种写法的正确性,于是我们可以带着欣赏的眼光来看这段代码了。
3.要承认我们的心智就这么多,脑袋就这么大,我们既不能一目十行也不能出口成章,所以不要写一言看不出什么意思的代码。
以上的想法都是建立在维护别人代码的痛苦,失落,沮丧,各种不爽,各种吐槽之上,所以代码规范是需要我们时刻关注的,在这里自己总结一些规范,告诫自己不要做始作俑者。
1.一个文件中只放一个类,类名同文件名,不要在一个文件中写好几个类,这样看的清楚。
2.不要在一个文件中写多于1000行的代码,除了那些比较大的实体类。其实我还想说超过500行看起来就有点累,但是在我们的系统中超过10000行的代码比比皆是。
3.一个方法的代码不要超过100行,其实我想说超过50行的方法看起来就有点累。但是在我们的系统中超过200行代码的方法比比皆是。
4.存储过程的代码也不要超过100行,不要在存储过程中写过多的业务逻辑,那是找死,但是在我们的系统中我还 * 的见过10000多行的存储过程,好宏伟啊!
5.避免写超过5个参数的方法,如果有请使用一个类或者结构来传。
6.一个方法只有一个return result; ,不要多次return结果,最好给返回结果赋值,最后return result;
7.不要给很简单的代码加注释,会有噪音的,会让人误解的,因为你写的大多数情况下很片面。
8.记录日志的时候不要到处都记,有条件的情况下针对客户一次操作(比如下单)只记录一条日志。
另外再这里列举自己对代码做的一些改进,不足之处欢迎大家指出。
1.参数过长使用缩进


a.
                    //获得保险策略信息
                    insuranceStrategy = InsuranceCommon.GetStrategyInsurance(appFltEntity.ProductSource.ToString(), strategyFlightAgency.ToString(), "", appFltEntity.Price.ToString(), appFltEntity.DirectFlightChannel, appFltEntity.Airline.DibitCode, appFltEntity.Flight, appFltEntity.DepartAirport.Code, appFltEntity.ArriveAirport.Code, appFltEntity.SubClass, appFltEntity.DepartTime, appFltEntity.DepartTime.Date, null);
b.
                    //获得保险策略信息
                    insuranceStrategy = InsuranceCommon.GetStrategyInsurance(appFltEntity.ProductSource.ToString(),
                                                                             strategyFlightAgency.ToString(),
                                                                             "",
                                                                             appFltEntity.Price.ToString(),
                                                                             appFltEntity.DirectFlightChannel,
                                                                             appFltEntity.Airline.DibitCode,
                                                                             appFltEntity.Flight,
                                                                             appFltEntity.DepartAirport.Code,
                                                                             appFltEntity.ArriveAirport.Code,
                                                                             appFltEntity.SubClass,
                                                                             appFltEntity.DepartTime,
                                                                             appFltEntity.DepartTime.Date,
                                                                             null);


2.if条件过长中使用缩进


a.
                if (IsDirectFlight && (this.CorpPayType == ExpenseType.OWN || this.AccountInfo.DirectOrdersQuoteMode == "I"))
                {
                    strategyFlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(appFltEntity.DirectFlightChannel);
                    //根据票台获得票台对应的城市
                    strategyCityID = InsuranceCommon.GetFlightAgencyCity(strategyFlightAgency);
                 }
b.
                if (IsDirectFlight &&
                    (this.CorpPayType == ExpenseType.OWN ||
                    this.AccountInfo.DirectOrdersQuoteMode == "I"))
                {
                    strategyFlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(appFltEntity.DirectFlightChannel);
                    //根据票台获得票台对应的城市
                    strategyCityID = InsuranceCommon.GetFlightAgencyCity(strategyFlightAgency);
                 }


3.使用三元表达式


a.
                        if (InsuranceInfoList != null && InsuranceInfoList.Count > 0 && InsuranceInfoList[0].GeneralDescription.Contains("e路泰康"))
                            collections.Set("IsElderCanBuyInsurance", "T");
                        else
                            collections.Set("IsElderCanBuyInsurance", "F");
b.
collections.Set("IsElderCanBuyInsurance", InsuranceInfoList != null && InsuranceInfoList.Count > 0 && InsuranceInfoList[0].GeneralDescription.Contains("e路泰康") ? "T" : "F");


4.使用蓝不大表达式


a.
                        InsuranceInfoList = InsuranceInfoList.FindAll(delegate(BookingInsuranceInfo iInfo)
                        {
                            return iInfo.TypeID == "C2C30";
                        });
b.
InsuranceInfoList = InsuranceInfoList.FindAll(a => a.TypeID == "C2C30");


5.使用switch表达式,见上面。
6.使用数组包含


a.
            if (wsFlt.ProductSource == 4 && !string.IsNullOrEmpty(wsFlt.DirectFlightChannel) && (wsFlt.DirectFlightChannel.ToUpper() == "HO-WS" or wsFlt.DirectFlightChannel.ToUpper() == "ZH-WS" or wsFlt.DirectFlightChannel.ToUpper() == "XT-WS")
                && directFlightCorporationList != null && directFlightCorporationList.Count > 0 && !directFlightCorporationList.Contains(corporationid))
            {
                return false;
            }
b.
            if (wsFlt.ProductSource == 4 &&
                new List<string>() { "HO-WS", "CZ-WS", "XT-WS" }.Contains(wsFlt.DirectFlightChannel.Trim().ToUpper()) &&
                directFlightCorporationList != null &&
                directFlightCorporationList.Count > 0 &&
                !directFlightCorporationList.Contains(corporationid))
            {
                return false;
            }


可以看到代码中也使用了缩进。
欢迎大家也列举自己遇到的代码简洁之道。

标签:C#,编码规范
0
投稿

猜你喜欢

  • C#多维数组学习使用

    2023-07-06 11:51:02
  • Android开发SavedState Jetpack状态保存利器

    2023-02-12 19:49:49
  • IntelliJ IDEA(2019)安装破解及HelloWorld案例(图文)

    2022-07-01 22:43:39
  • Spring boot+mybatis+thymeleaf 实现登录注册增删改查功能的示例代码

    2023-10-05 04:20:53
  • 基于C#调用c++Dll结构体数组指针的问题详解

    2021-12-10 23:16:41
  • C#实现基于任务的异步编程模式

    2023-01-08 19:21:15
  • 详解Unity日志打印工具功能

    2022-03-27 09:34:19
  • Java8 使用 stream().sorted()对List集合进行排序的操作

    2022-11-23 20:57:11
  • 解决SpringBoot自定义拦截器和跨域配置冲突的问题

    2022-01-31 04:59:29
  • Java锁擦除与锁粗化概念和使用详解

    2022-02-09 15:32:30
  • Android画画板的制作方法

    2022-08-25 06:08:07
  • Spring JPA find单表查询方法示例详解

    2022-11-03 19:43:38
  • 微服务如何通过feign.RequestInterceptor传递参数

    2022-02-26 00:28:20
  • C++中用指向数组的指针作函数参数

    2022-08-27 23:11:33
  • Java编程中利用InetAddress类确定特殊IP地址的方法

    2021-06-24 23:00:12
  • java文件上传下载代码实例

    2023-11-10 05:06:14
  • Android Studio ADB网络调试汇总

    2023-07-13 22:10:07
  • java Semaphore共享锁实现原理解析

    2021-11-02 23:12:38
  • SpringBoot整合Security安全框架实现控制权限

    2022-10-03 14:37:15
  • Java 8中日期和时间的处理方法

    2021-09-07 15:37:58
  • asp之家 软件编程 m.aspxhome.com