zoukankan      html  css  js  c++  java
  • Effective C# 学习笔记(十) 用可选参数尽量减少方法重载

    先看个例子,创建word文档,并在其中写一行话

    var wasted = Type.Missing;

    var wordApp = new

    Microsoft.Office.Interop.Word.Application();

    wordApp.Visible = true;

    Documents docs = wordApp.Documents;

    //这个方法传了四个参数,但都不是开发人员想传的,能不能在需要时再传有用的参数,而不必每次都补空值呢?

    Document doc = docs.Add(ref wasted,

    ref wasted, ref wasted, ref wasted);

    Range range = doc.Range(0, 0);

    range.InsertAfter("Testing, testing, testing. . .");

     

    下面这个代码就展现了可选参数的作用

     

    var wordApp = new

    Microsoft.Office.Interop.Word.Application();

    wordApp.Visible = true;

    Documents docs = wordApp.Documents;

    //简介很多吧? :)

    Document doc = docs.Add();

    Range range = doc.Range(0, 0);

    range.InsertAfter("Testing, testing, testing. . .");

     

    要想独立地定义些参数,而不想给其他参数都付空值可以利用C#的命名参数的新特性

    var wordApp = new

    Microsoft.Office.Interop.Word.Application();

    wordApp.Visible = true;

    Documents docs = wordApp.Documents;

    object docType = WdNewDocumentType.wdNewWebPage;

    //使用了命名参数 DocumentType,这样的可读性也很好,你知道 docType参数到底是传给谁了

    Document doc = docs.Add(DocumentType : ref docType);

    Range range = doc.Range(0, 0);

    range.InsertAfter("Testing, testing, testing. . .");

     

    注意:使用命名参数的会存在一个风险,那就是当改变了某个方法的参数名称时,需重新使用该方法的参数名称,重新编译程序

  • 相关阅读:
    【BZOJ】1552/3506 [Cerc2007]robotic sort
    【BZOJ】1014 [JSOI2008]火星人prefix
    【BZOJ】1500: [NOI2005]维修数列
    【51NOD-0】1046 A^B Mod C
    【51NOD-0】1019 逆序数
    【51NOD-0】1018 排序
    【51NOD-0】1012 最小公倍数LCM
    The Grove(poj 3182)
    Iahub and Permutations(codeforces 314c)
    多边形之战(bzoj 2927)
  • 原文地址:https://www.cnblogs.com/haokaibo/p/2097713.html
Copyright © 2011-2022 走看看