Effective C# 学习笔记(十) 用可选参数尽量减少方法重载
2011-07-04 20:30
309 查看
先看个例子,创建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. . .");
注意:使用命名参数的会存在一个风险,那就是当改变了某个方法的参数名称时,需重新使用该方法的参数名称,重新编译程序
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. . .");
注意:使用命名参数的会存在一个风险,那就是当改变了某个方法的参数名称时,需重新使用该方法的参数名称,重新编译程序
相关文章推荐
- 《Effective C#》读书笔记——条目10:使用可选参数减少方法重载的数量<C#语言习惯>
- Effective C# 学习笔记(十四) 尽量减少重复性的初始化逻辑
- Effective C# 学习笔记(四十五)减少装箱拆箱行为
- Effective C# 学习笔记(三十九) 使用Dynamic处理范型参数的运行时类型
- Effective C# 学习笔记(四十)使用Dynamic处理匿名类型参数
- 《C#入门到精通》学习笔记 -- 命名参数与可选参数
- Effective C# 学习笔记(十一)尽量缩减函数体的大小,提高运行效率
- [读书笔记]C#学习笔记七: C#4.0中微小改动-可选参数,泛型的可变性
- [读书笔记]C#学习笔记七: C#4.0中微小改动-可选参数,泛型的可变性
- Effective C# 学习笔记(十六)尽量少的创建对象,给GC减减负
- C#学习基础--可选参数、命名参数
- Effective C# 学习笔记(四十三)使用Expression处理绑定(属性值更改)事件
- C++ 学习笔记(四) GCC常用参数
- 转:Android 学习笔记 Contacts (一)ContentResolver query 参数详解
- Struts2_学习笔记(三)--------Action接收参数的四种方法
- JavaWeb学习笔记-java基础-5-可变参数
- OpenCv学习笔记(二)--Mat矩阵(图像容器)的创建及CV_8UC1,CV_8UC2等参数详解
- CNN学习笔记之LeNet-5模型各层参数理解
- DL学习笔记【9】caffe参数调节-全连接层
- loadrunner学习笔记之参数设置