没有合适的资源?快使用搜索试试~ 我知道了~
Professional C#, 3rd Edition_AppC_C# for Java Developers.pdf
需积分: 10 23 下载量 64 浏览量
2008-01-03
07:35:38
上传
评论
收藏 377KB PDF 举报
温馨提示
试读
28页
“Professional C#, 3rd Edition“ 经典名著“C#高级编程(第3版)”一书的附录C:C#与Java开发者
资源推荐
资源详情
资源评论
C# for Java Developers
At first glance, Java developers might not get particularly excited about C# code, because of the
syntactical similarity between it and Java. However, look more closely and you will see subtle yet
significant differences: features such as operator overloading, indexers, delegates, properties, and
type safe enumerations in C#.
This appendix focuses on applying much-loved Java programming tricks to C# code, highlighting
features that C# adds to the picture, and pointing out tricks that C# cannot do (although you won’t
find many of those). Of course, we assume that as a reader of this appendix, you are a professional
Java developer; so we will not go into too much detail when describing the Java language.
Starting Out
Let’s take a look at the infamous “Hello World!” example in Java:
public class Hello {
public static void main(String args []) {
System.out.println(“Hello world! This is Java Code!”);
}
}
The corresponding C# code for this is as follows:
using System;
public class Hello
{
public static void Main(string [] args)
{
System.Console.WriteLine(“Hello world! This is C# code!”);
}
}
557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1225
The first thing that you’ll notice is that the two appear to be very similar syntactically and both lan-
guages are case-sensitive. C# is object-oriented like Java, and all functionality must be placed inside a
class (declared by the keyword
class). These classes can contain methods, constructors, and fields just
as Java classes can, and a C# class can inherit methods and fields from another class or interface as in
Java. The implementation of classes and methods is similar in both languages.
C# code blocks are enclosed by braces just as in Java. The entry point to a C# application is the static
Main() method, as required by the compiler (similar to Java but note the uppercase “M”). Also note that
only one class in the application can have a
Main() method. Similar to Java, the static keyword allows
for the method to be called without creating an instance of the class first. For the
Main() method in C#
you have the choice of either a
void or int return type. void specifies that the method does not return a
value and
int specifies that it returns an integer type.
The
using keyword in C# corresponds to the import keyword in Java. Therefore, in the C# code above,
we are essentially importing the C# equivalent of a class package called
System. In C#, a class package is
called a namespace, and we will look more closely at these in the next section.
Note that although we have written it with a lowercase s here, in C# the string type can also be written
with a capital S as String. You will also notice that the array rank specifier (
[]) has been shifted from in
front of the
args variable in the Java example, to between the string type and args variable in the C#
sample. In fact, this specifier can occur before or after the variable in Java. However, in C#, the array
rank specifier must appear before the variable name because an array is actually a type of its own indi-
cated by type
[]. We’ll discuss arrays in more depth a bit later.
Finally, as you might expect, the names of methods tend to differ between the languages. For example,
in Java we would use
System.out.println() to display text in the command console. The equivalent
to this method in C# is
System.Console.WriteLine().
Compiling and Running C# Code
In Chapter 2, we noted that like Java code, C# source code is compiled in two stages: first to
Intermediate Language (IL), and then to native code. To run the previous C# code, you need to save it
with an appropriate filename (for example, HelloWorld) and file extension .cs, and then compile it to IL
using the csc command:
csc HelloWorld.cs
The next step is to compile the IL to native code and run the example. To do this, just type the name of
the file, without the extension (as we would with Java code):
HelloWorld
Hello world! This is C# code!
Namespaces
While Java classes reside in logical divisions referred to as packages, C# (and other managed) classes are
grouped together into namespaces. Packages and namespaces differ significantly in their implementation.
A Java class that you want to make part of the
com.samples package, for example, must have package
com.samples; as the first line of code in the file. This is, of course, excluding any comments. Any code
1226
Appendix C
557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1226
within that file automatically becomes a part of the specified package. Also, a Java package name is asso-
ciated with the folder containing the class file in that they must have the same name. The
com.samples
package must therefore be in class files that exist in the com/samples folder. Let’s take a look at some
examples of how packages work in Java:
package java2csharp.javasamples;
public class Hello {
public static void main(String args []) {
System.out.println(“Hello world! This is Java Code!”);
}
}
The following list provides examples of how the previous code could be referenced or executed. This list
assumes that the class file has been made available to the JRE:
❑ From the command line:
java java2csharp.javasamples.Hello
❑ As a direct reference in the code:
public class Referencer {
java2csharp.javasamples.Hello myHello = new java2csharp.samples.Hello();
❑ By utilizing the import directive one could omit fully qualified package names, so Referencer
could also be written as:
import java2csharp.javasamples.*;
public class Referencer {
Hello myHello = new Hello();
}
Wrapping a class in a namespace is achieved in C# by using the namespace keyword with an identifier,
and enveloping the target class in brackets. Here is an example:
namespace java2csharp.csharpsamples
{
using System;
public class Hello
{
public static void Main(string [] args)
{
System.Console.WriteLine(“Hello world! This is C# code!”);
}
}
}
As you can see, we delimit layers of namespaces using the . operator, as in Java. Note that C# does not
require an asterisk (*) needed in C#—applying the
using directive implicitly imports all elements of the
specified namespace. You will also have noticed the major difference from Java here: the use of name-
space parentheses in which we place classes associated with the namespace. The advantage of using the
parentheses like this is that we then disassociate package names from directory structures: feasibly we
1227
C# for Java Developers
557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1227
could place a file containing this namespace anywhere within the directory as long as the CLR recog-
nizes it. Therefore, it also enables us to call the file containing these classes anything we wish (it doesn’t
have to be the same name as the class as in Java); we can have more than one public class defined per
file; and we can split the classes defined in this namespace into different files in different parts of the
directory structure, as long as the namespace declaration appears in each of the files.
We can also introduce multiple namespaces in the same file with no restriction. We could, for example,
add the definition of a new class and place it in a new namespace in the same file and still not be outside
the bounds of the language:
namespace java2csharp.csharpsamples
{
using System;
public class Hello
{
public static void Main(string [] args)
{
System.Console.WriteLine(“Hello world! This is C# code!”);
}
}
}
namespace java2csharp.morecsharpsamples
{
using System;
public class AnotherHello
{
public static void Main(string [] args)
{
System.Console.WriteLine(“Hello again! This is more C# code!”);
}
}
}
As we pointed out in the previous section, classes from a particular namespace can be imported into
another namespace with the
using keyword. We can see that we import classes from the System name-
space (the top level .NET Base Class namespace) into both namespaces above. We can also import classes
from other namespaces directly into our classes by referring to the imported class using its full name
(namespace included), in a similar way to using direct referencing of classes in Java code.
Namespaces may also be defined within other namespaces. This type of flexibility is impossible in Java
without having to create a subdirectory. We could change the previous example so that the
AnotherHello
class is in the java2csharp.csharpsamples.hellosamples namespace:
namespace java2csharp.csharpsamples
{
namespace hellosamples
{
using System;
public class AnotherHello
{
public static void Main(string [] args)
1228
Appendix C
557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1228
{
System.Console.WriteLine(“Hello again! This is more C# code!”);
}
}
}
}
Java classes are part of a package; all classes created are part of the default package. C# mimics this func-
tionality. Even if you do not declare one, a default namespace is created for you. It is present in every file
and available for use in named namespaces. Just as in Java you cannot change package information, in
C# namespaces cannot be modified either. Packages can span multiple files in the same folder; name-
spaces can span multiple files in any number of folders, and even multiple assemblies (the name given
to code libraries in .NET), as discussed in Chapter 13.
Note that the default accessibility for types inside a namespace is internal. You must specify types as
public if you want them available without full qualification; however, we strongly advise against this
practice. No other access modifiers are allowed. In Java, internal package types may also be marked as
final or abstract or not marked at all (this default access makes them available only to consumers
inside the package). Access modifiers are discussed later in this appendix.
One final feature of namespaces not available to Java packages is that they may be given a
using alias.
using aliases make it very easy to qualify an identifier to a namespace or class. The syntax is simple.
Suppose you had a namespace
Very.Very.Long.NameSpace.Name. You could define and use a using
alias (here VVLNN) for the namespace as follows:
using VVLNN = Very.Very.Long.Namespace.Name;
Declaring Variables
C# follows a similar scheme of variable declaration to Java, where the declaration consists of a datatype
keyword and followed by the name of the variable to hold that datatype. For example, to declare an
integer (
int) variable called myInt, we would use the following code:
int myInt;
Identifiers are the names we give to classes, objects, class members, and variables. Raw keywords, dis-
cussed in the next section, can neither be Java nor C# identifiers; however, in C# you can use keywords
as variable names by prefixing the name with
@. Note that this exception is only with keywords and
does not allow the breaking of any other rules. Although identifiers may have letters and numbers, the
first letter of the identifier in both C# and Java must not be a number. Here are some valid and invalid
examples of variable declaration:
int 7x; //invalid, number cannot start identifier
int x7; //valid, number may be part of identifier
int x; //valid
int x$; //invalid, no symbols allowed
int @class; //valid, prefix @ allows it to be used as an identifier
int @7k; //invalid, prefix @ only works for keywords
1229
C# for Java Developers
557599 AppC_BC03.qxd 4/28/04 10:49 AM Page 1229
剩余27页未读,继续阅读
资源评论
baohai9999
- 粉丝: 0
- 资源: 48
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功