饭饭TXT > 学习管理 > 《Visual Studio 2010 高级编程(英文出书版)》作者:Nick Randolph/等【完结】 > [Visual.Studio.2010.高级编程].Professional.Visual.Studio.2010.txt

第 49 页

作者:Nick Randolph/等 当前章节:15391 字 更新时间:2026-6-18 14:51

anonymous methods) or an expression tree (discussed further in Chapter 29 on LINQ). In VB you

now have the ability to declare single and multiline anonymous methods.

The following code snippet illustrates a number of features of working with anonymous methods

in VB. In the first line an anonymous function is declared that accepts a name parameter and

returns a Boolean. Type inference is used to determine that the name parameter should be a string

and in fact in this case the As Boolean can be omitted because the return type can also be inferred.

If the inferred input type is wrong or you wish to make your code more readable you can also

specify the type of the input parameter.

Vb

Dim exp = Function(name) As Boolean

Console.WriteLine("Hello " & name)

Return name.length > 10

End Function

Dim exp2 = Sub(name)

If exp(name) Then

Console.WriteLine(name & " is longer than 10 characters")

End If

End Sub

exp("Fred")

Dim names = {"Fred", "Joe", "Sandra"}

Array.ForEach(names, exp2)

Array.ForEach(names, Sub(name As String) Console.WriteLine(name))

Code snippet MainForm.vb

The second line illustrates that you can create an anonymous method with no return type, also

know as a Sub in VB. Both lines return a delegate that can be invoked by supplying a parameter,

illustrated in the next two lines. The final line illustrates how you can define an anonymous

method in line as part of a method call. Note here that the abbreviated form has been used, as the

322 .

chaPter 16 lAnguAge-SpeciFic FeATureS

Sub is a single line. If your method has multiple lines, you need to use the full notation that includes

an End Sub or End Function, depending on whether it has a return value.

implicit line continuation

Where possible, the VB compiler will infer line continuation. For example, you can now write the

following with no line continuation characters:

Vb

Public Function LongMethodDeclaration(ByVal parameterOne As Integer,

ByVal parameterTwo As Integer,

ByVal parameterThree As Integer,

ByVal parameterFour As Integer,

ByVal parameterFive As Integer,

ByVal parameterSix As Integer) As Integer

Return parameterOne + parameterTwo + parameterThree +

parameterFour + parameterFive + parameterSix

End Function

Code snippet MainForm.vb

In some cases, a line continuation character is still required. For example, if you wanted the

parameter list to start on a new line:

Vb

Public Function LongMethodDeclaration _

(ByVal parameterOne As Integer,

ByVal parameterTwo As Integer,

Implicit line continuation makes writing LINQ expressions with VB much easier, as you can break

up the expression over multiple lines without having to add the line break character each time.

automatic Properties with initial Values

When defining a class, it is good practice to use encapsulation to hide or encapsulate the

functionality of your class. The idea is that if you need to change the implementation, you can do so

without affecting other code that uses that class. As such, it is recommended that where you want to

expose a field, it should be done via a property. The property can simply be a getter/setter, or it can

contain additional functionality, for example, that raises an event when the property value changes.

This practice has resulted in large amounts of repetitive code where a property is declared along

with a backing field. Although this has been made easier with Visual Studio snippets, it still results

in code that is overly verbose.

In Visual Studio 2010, VB now not only has automatic properties — properties that automatically

implement the backing field — it also enables you to declare an initial value for the property in

the same way as you would for a field. The initial value is set by calling the property setter after

the object instance is initialized but prior to any constructor being invoked. The following code

illustrates this with the MaximumWordCount property:

Visual Basic .

323

Vb

Public Property MaximumWordCount As Integer = 10

Public Sub New()

MessageBox.Show("The maximum word count is " & MaximumWordCount)

MessageBox.Show("The maximum word count is " & _MaximumWordCount)

Code snippet MainForm.vb

Nowhere in this code snippet is the _MaximumWordCount field declared. VB exposes the backing

field used by the automatic property by simply prepending the property name with an underscore.

Although it is not recommended, you can access the field directly from within your class because it

is declared with a scope of Private.

collection initializers and array literals

VB now has a compact notation for specifying arrays, illustrated in the following code snippet:

Vb

' Single dimension arrays

Dim a = {56, 34, 29, 12, 35, 872, 34, 12, 66} 'Integer()

Dim b = {1, 5, 3.54, 3.5} 'Double()

Dim c = {"Betty", "Frank"} 'String()

Dim d = {1, "123", New Animal} 'Object()

'Multi-dimension arrays

Dim e = {{1, 2, 3},

{4, 5, 6}} 'non-jagged array (ie Integer(,) )

Dim f = {({1, 2, 3}),

({4}),

({5, 6, 7})} 'jagged array (ie Integer()())

Code snippet MainForm.vb

Note that the type of the array is inferred from the type of each of the constituent values. As such,

the array b is an array of Double because this allows both the first two values, which are Integers,

and the remaining values to be inserted. The Object array will raise an error if Option Strict is on.

Lists and Dictionaries can also be initialized using a similar compact notation:

Vb

Private listOfNames As New List(Of String) From {"Nick", "Dave", "Mike", "Chris"}

Private cityLookup As New Dictionary(Of String, String) _

From {{"Nick", "Sydney"},

{"Dave", "Perth"},

{"Mike", "Perth"},

{"Chris", "Sydney"}}

Code snippet MainForm.vb

324 .

chaPter 16 lAnguAge-SpeciFic FeATureS

The initialization of the List and Dictionary is done by invoking the Add method on the newly

created instance. You can use a similar compact syntax to add your own object types to a List by

creating an extension method, named Add, that will convert a set of input values into an instance of

your class.

Vb

Private listOfWeirdObjects As New List(Of MyListClass) From {{"Boo", 45, 67, 4.5},

{"Foo", 29, 34, 7.4}}

Public Module Extensions

<Extension()>

Sub Add(ByVal list As List(Of MyListClass),

ByVal Name As String,

ByVal Height As Integer,

ByVal Weight As Integer,

ByVal Width As Double)

list.Add(New MyListClass With {

.Name = Name,

.Height = Height,

.Weight = Weight,

.Width = Width

})

End Sub

End Module

Code snippet MainForm.vb

nullable optional Parameters

In the past it was not possible for nullable parameters to be optional. Now they can be, allowing

you to define methods such as the following:

Vb

Public Sub New()

MethodWithOptionalParameters(5, parameterThree:=6)

End Sub

Public Function MethodWithOptionalParameters _

(Optional ByVal parameterOne As Integer? = Nothing,

Optional ByVal parameterTwo As Integer? = 0,

Optional ByVal parameterThree As Integer? = Nothing) _

As Integer

Code snippet MainForm.vb

C# .

325

As you can see from the code, for the optional parameters you need to define a default value. Also,

when calling the method you may need to use parameter naming (as in parameterThree:=) if you

wish to skip an optional parameter.

Visual basic PowerPacks

One of the challenges often put forward by VB6 developers is that doing tasks in .NET requires

many more steps or is more complex than it was in VB6. To encourage VB6 developers across to

the .NET Framework, VB introduced the My namespace, which provides a set of shortcut methods

to get frequently performed tasks done.

The VB team has also released the Visual

Basic PowerPacks for previous versions

of Visual Studio that add a number of

useful controls and other classes to aid

VB developers.

Visual Studio 2010 ships with the Visual

Basic PowerPacks. As you can see in

Figure 16-3, an additional tab in the

Toolbox contains a number of drawing

controls such as Line, Oval, and Rectangle.

These can be used to generate simple

graphics, such as the one on the right-hand

side of Figure 16-3.

Although the Visual Basic PowerPacks are available by default to VB developers, there is no reason

why C# developers can’t access the same controls. To use these controls in a C# project, simply add

a reference to the PowerPacks assembly and then add the controls to your Toolbox. From there you

can use them on any Windows Forms application.

c#

In this iteration of the C# language there are only a couple of new features that mainly focus around

the ability to interop with both native and dynamic languages.

late binding with dynamic lookup

Interoperability with other languages/technologies can often be quite painful, particularly with

dynamic languages where it is not always known up front what methods a class may contain. In the

past it was possible to execute these calls, but it often required a fairly in-depth understanding of

reflection, and even then required many calls to invoke a single method. The new dynamic keyword

can be used to allow methods to be late bound:

c#

public class DynamicClass{}

public class MoreDynamic : DynamicClass{

fiGure 16-3

326 .

chaPter 16 lAnguAge-SpeciFic FeATureS

public void SimpleMethod(){

MessageBox.Show("Dynamic Invoked");

}

}

public MainForm(){

InitializeComponent();

dynamic lateBound = CreateDynamic();

lateBound.SimpleMethod();

}

public object CreateDynamic(){

return new MoreDynamic();

}

Code snippet MainForm.cs

In this code example the CreateDynamic method returns a MoreDynamic object as just an object. By

declaring the lateBound object using the dynamic keyword it is possible to invoke the SimpleMethod

the same way as if the method was declared on the object. Without this keyword, the static type

checker would be invoked and a compile error would be thrown because the SimpleMethod is not

declared on object (which is returned from CreateDynamic and thus would be the inferred type of

the lateBound variable).

One of the challenges with using the dynamic keyword is that the onus is now

firmly on you to make sure you get the method naming, type, and number of

parameters correct to ensure your code doesn’t fail at run time. The dynamic

keyword effectively blocks the static type checking at compile time, deferring it to

the point where the code is executed.

named and optional Parameters

Two features that have been noticeably absent from C# are the ability to define optional parameters

and to specify parameters using their names. Both these features contribute to making code more

usable and more readable because they do away with unnecessary bloat (that is, specifying null for

parameters you don’t need/want to specify or having additional method overloads to effectively

define optional parameters) and allow parameter values to be named.

c#

public MainForm(){

InitializeComponent();

var output = MethodWithOptionalParameters(parameterTwo: 15);

}

f# .

327

public int MethodWithOptionalParameters(int? parameterOne = null,

int parameterTwo = 5){

return (parameterOne   0) + parameterTwo;

}

Code snippet MainForm.cs

In this code both parameters are optional: the first being a nullable int with a default value of null,

the second being a normal int with a default value of 5. Parameters become optional when a default

value is specified as part of the method signature. When calling a method with optional parameters,

those parameters can simply be omitted. Regardless of whether parameters are optional, you can

name each of the parameter values so that someone reading your code can easily understand what

the parameter values correspond to. This is particularly important if you are supplying a constant

value, as is the case in the preceding code snippet, where the meaning of the constant value is

not immediately obvious.

The use of named and optional parameters is particularly useful when working with COM

interfaces. These quite often have a number of optional parameters that in the past would have had

to be specified. This is no longer the case because those parameters can simply be omitted. Using

named parameter values makes it clear which parameters you are supplying.

Calling methods using named parameters can make your code more brittle to

changes. For example, say you access a third-party control that has a method

with a single parameter called height. If the control vendor does a version

update and changes the parameter name to controlHeight, even if the method

signature didn’t change, your code will no longer be able to locate the height

parameter, so it will fail.

f#

F# (pronounced F Sharp) is a relatively new language incubated out of Microsoft Research

in Cambridge, England, by the guy that brought generics to the .NET Framework, Don

Syme. Microsoft’s Developer Division recently welcomed F# to the Visual Studio range of

supported languages and it ships in the box with Visual Studio 2010. F# is a multi-paradigm

functional language. This means it’s primarily a functional language, but supports other flavors

of programming, such as imperative and object-oriented programming styles.

your first f# Program

Fire up Visual Studio 2010 and create a new F# project. As Figure 16-4 shows, the F#

Application template is located in the Visual F# node in the New Project dialog. Give it a

name and click OK.

328 .

chaPter 16 lAnguAge-SpeciFic FeATureS

目录
设置
设置
阅读主题
字体风格
雅黑 宋体 楷书 卡通
字体大小
适中 偏大 超大
保存设置
恢复默认
手机
手机阅读
扫码获取链接,使用浏览器打开
书架同步,随时随地,手机阅读
首 页 < 上一章 章节列表 下一章 > 尾 页