首页 > 编程 > C# > 正文

C#的编码规范详细说明

2020-01-24 03:11:03
字体:
来源:转载
供稿:网友
首先我们要明白一下几点,
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;
            }

可以看到代码中也使用了缩进。
欢迎大家也列举自己遇到的代码简洁之道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表