惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
V
Visual Studio Blog
P
Privacy International News Feed
月光博客
月光博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
Lohrmann on Cybersecurity
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
Webroot Blog
Webroot Blog
T
Threatpost
宝玉的分享
宝玉的分享
The Last Watchdog
The Last Watchdog
小众软件
小众软件
L
LINUX DO - 最新话题
C
Cisco Blogs
T
Troy Hunt's Blog
Schneier on Security
Schneier on Security
酷 壳 – CoolShell
酷 壳 – CoolShell
www.infosecurity-magazine.com
www.infosecurity-magazine.com
雷峰网
雷峰网
G
GRAHAM CLULEY
有赞技术团队
有赞技术团队
Know Your Adversary
Know Your Adversary
博客园 - 叶小钗
罗磊的独立博客
V
V2EX
博客园 - Franky
P
Proofpoint News Feed
SecWiki News
SecWiki News
腾讯CDC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Jina AI
Jina AI
博客园 - 三生石上(FineUI控件)
S
Secure Thoughts
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google DeepMind News
Google DeepMind News
Attack and Defense Labs
Attack and Defense Labs
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
PCI Perspectives
PCI Perspectives
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
aimingoo的专栏
aimingoo的专栏
Cisco Talos Blog
Cisco Talos Blog
N
News and Events Feed by Topic
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
SegmentFault 最新的问题

博客园 - 中尉

开源后的.Net 如何选择使用 创建多个Oracle数据库及相应的实例 DB2和Oracle区别 宝化项目结题 用户中心 - 博客园 用户中心 - 博客园 用户中心 - 博客园 VB.NET and C# Comparison 小小议下WINFORM应用框架开发(一) 整合TextBox与Label 创建新控件--EFLabelText 摩斯密码 用户中心 - 博客园 用户中心 - 博客园 ProC连接Oracle 关于博文转载 如何成为优秀的软件人才 休息下 从DLL中加载启动窗体 关于系统设计分层
Java and C# Comparison
中尉 · 2011-10-19 · via 博客园 - 中尉

Java and C# Comparison
This is a quick reference guide to highlight some key syntactical differences between Java and C#.
This is not a complete overview of either language. Hope you find this useful!

Java Program Structure C#
package hello;

public class HelloWorld {
   public static void main(String[] args) {
      String name = "Java";

     
      if (args.length == 1)
         name = args[0];

      System.out.println("Hello, " + name + "!");
    }
}

using System;

namespace Hello {
   public class HelloWorld {
      public static void Main(string[] args) {
         string name = "C#";

        
         if (args.Length == 1)
            name = args[0];

         Console.WriteLine("Hello, " + name + "!");
      }
   }
}

// Single line
/* Multiple
    line  */

/** Javadoc documentation comments */
// Single line
/* Multiple
    line  */

/// XML comments on a single line
/** XML comments on multiple lines */


boolean
byte
char
short, int, long
float, double


Object  
String
arrays, classes, interfaces


int x = 123;
String y = Integer.toString(x); 


y = "456"; 
x = Integer.parseInt(y);  


double z = 3.5;
x = (int) z;  


bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double, decimal
structures, enumerations


object   
string
arrays, classes, interfaces, delegates


int x = 123;
String y = x.ToString(); 


y = "456";
x = int.Parse(y);  


double z = 3.5;
x = (int) z;  

// May be initialized in a constructor
final double PI = 3.14;
const double PI = 3.14;


readonly int MAX_HEIGHT = 9;

enum Action {Start, Stop, Rewind, Forward};


enum Status {
  Flunk(50), Pass(70), Excel(90);
  private final int value;
  Status(int value) { this.value = value; }
  public int value() { return value; }
};

Action a = Action.Stop;
if (a != Action.Start)
  System.out.println(a);              

Status s = Status.Pass;
System.out.println(s.value());

enum Action {Start, Stop, Rewind, Forward};

enum Status {Flunk = 50, Pass = 70, Excel = 90};

Action a = Action.Stop;
if (a != Action.Start)
  Console.WriteLine(a);      

Status s = Status.Pass;
Console.WriteLine((int) s);


==  <  >  <=  >=  !=


+  -  *  /

/  
Math.Pow(x, y)


=  +=  -=  *=  /=   %=   &=  |=  ^=  <<=  >>=  >>>=  ++  --


&  |  ^   ~  <<  >>  >>>


&&  ||  &  |   ^   !

Note: && and || perform short-circuit logical evaluations


+


==  <  >  <=  >=  !=


+  -  *  /

/  
Math.Pow(x, y)


=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --


&  |  ^   ~  <<  >>


&&  ||  &  |   ^   !

Note: && and || perform short-circuit logical evaluations


+

greeting = age < 20 ? "What's up?" : "Hello";

if (x < y)
  System.out.println("greater");

if (x != 100) {   
  x *= 5;
  y *= 2;
}
else
  z *= 6;

int selection = 2;
switch (selection) {     // Must be byte, short, int, char, or enum
  case 1: x++;            // Falls through to next case if no break
  case 2: y++;   break;
  case 3: z++;   break;
  default: other++;
}

greeting = age < 20 ? "What's up?" : "Hello";

if (x < y) 
  Console.WriteLine("greater");

if (x != 100) {   
  x *= 5;
  y *= 2;
}
else
  z *= 6;

string color = "red";
switch (color) {                          // Can be any predefined type
  case "red":    r++;    break;

// break is mandatory; no fall-through
  case "blue":   b++;   break;
  case "green": g++;   break;
  default: other++;     break;       // break necessary on default
}

while (i < 10)
  i++;

for (i = 2; i <= 10; i += 2) 
  System.out.println(i);

do
  i++;
while (i < 10);

for (int i : numArray)   
  sum += i;


import java.util.ArrayList;
ArrayList<Object> list = new ArrayList<Object>();
list.add(10);    
list.add("Bisons");
list.add(2.3);   

for (Object o : list)
  System.out.println(o);

while (i < 10)
  i++;

for (i = 2; i <= 10; i += 2)
  Console.WriteLine(i);

do
  i++;
while (i < 10);

foreach (int i in numArray) 
  sum += i;

// foreach can be used to iterate through any collection 
using System.Collections;
ArrayList list = new ArrayList();
list.Add(10);
list.Add("Bisons");
list.Add(2.3);

foreach (Object o in list)
  Console.WriteLine(o);

int nums[] = {1, 2, 3};   or   int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++)
  System.out.println(nums[i]);

String names[] = new String[5];
names[0] = "David";

float twoD[][] = new float[rows][cols];
twoD[2][0] = 4.5;

int[][] jagged = new int[5][];
jagged[0] = new int[5];
jagged[1] = new int[2];
jagged[2] = new int[3];
jagged[0][4] = 5;

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
  Console.WriteLine(nums[i]);

string[] names = new string[5];
names[0] = "David";

float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;

int[][] jagged = new int[3][] {
    new int[5], new int[2], new int[3] };
jagged[0][4] = 5;

// Return single value
int Add(int x, int y) {
   return x + y;
}

int sum = Add(2, 3);

// Return no value
void PrintSum(int x, int y) {
   System.out.println(x + y);
}

PrintSum(2, 3); 

void TestFunc(int x, Point p) {
   x++;
   p.x++;      
   p = null;   
}

class Point {
   public int x, y;
}

Point p = new Point();
p.x = 2;
int a = 1;
TestFunc(a, p);
System.out.println(a + " " + p.x + " " + (p == null) ); 


int Sum(int ... nums) {
  int sum = 0;
  for (int i : nums)
    sum += i;
  return sum;
}

int total = Sum(4, 3, 2, 1);  

// Return single value
int Add(int x, int y) {
   return x + y;
}

int sum = Add(2, 3);

// Return no value
void PrintSum(int x, int y) {
   Console.WriteLine(x + y);
}

PrintSum(2, 3); 


void TestFunc(int x, ref int y, out int z, Point p1, ref Point p2) {
   x++;  y++;  z = 5;
   p1.x++;           
   p1 = null;   
   p2 = null;  
}

class Point {
   public int x, y;
}

Point p1 = new Point();
Point p2 = new Point();
p1.x = 2;
int a = 1, b = 1, c;  
TestFunc(a, ref b, out c, p1, ref p2);
Console.WriteLine("{0} {1} {2} {3} {4}",
   a, b, c, p1.x, p2 == null);  


int Sum(params int[] nums) {
  int sum = 0;
  foreach (int i in nums)
    sum += i;
  return sum;
}

int total = Sum(4, 3, 2, 1);   // returns 10


String school = "Harding ";
school = school + "University";  


String mascot = "Bisons";
if (mascot == "Bisons")    
if (mascot.equals("Bisons"))  
if (mascot.equalsIgnoreCase("BISONS"))  
if (mascot.compareTo("Bisons") == 0)  

System.out.println(mascot.substring(2, 5));  


java.util.Calendar c = new java.util.GregorianCalendar(1973, 10, 12);
String s = String.format("My birthday: %1$tb %1$te, %1$tY", c);


StringBuffer buffer = new StringBuffer("two ");
buffer.append("three ");
buffer.insert(0, "one ");
buffer.replace(4, 7, "TWO");
System.out.println(buffer);    


string school = "Harding ";
school = school + "University";  


string mascot = "Bisons";
if (mascot == "Bisons")   
if (mascot.Equals("Bisons"))   
if (mascot.ToUpper().Equals("BISONS"))  
if (mascot.CompareTo("Bisons") == 0)   

Console.WriteLine(mascot.Substring(2, 3));   


DateTime dt = new DateTime(1973, 10, 12);
string s = "My birthday: " + dt.ToString("MMM dd, yyyy");


System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer);    

Java Exception Handling C#


Exception ex = new Exception("Something is really wrong.");
throw ex;  

try {
  y = 0;
  x = 10 / y;
} catch (Exception ex) {
  System.out.println(ex.getMessage()); 
} finally {
 
}

Exception up = new Exception("Something is really wrong.");
throw up; 


try
{
  y = 0;
  x = 10 / y;
} catch (Exception ex) {     
  Console.WriteLine(ex.Message);
} finally {
 
}

package harding.compsci.graphics;


import harding.compsci.graphics.Rectangle;


import harding.compsci.graphics.*;  

namespace Harding.Compsci.Graphics {
  ...
}

namespace Harding {
  namespace Compsci {
    namespace Graphics {
      ...
    }
  }
}


using Rectangle = Harding.CompSci.Graphics.Rectangle;


using Harding.Compsci.Graphics;

Java Classes / Interfaces C#


public
private
protected
static


class FootballGame extends Competition {
  ...
}


interface IAlarmClock {
  ...
}


interface IAlarmClock extends IClock {
  ...
}


class WristWatch implements IAlarmClock, ITimer {
   ...
}


public
private
internal
protected
protected internal
static


class FootballGame : Competition {
  ...
}


interface IAlarmClock {
  ...
}


interface IAlarmClock : IClock {
  ...
}


class WristWatch : IAlarmClock, ITimer {
   ...
}

Java Constructors / Destructors C#

class SuperHero {
  private int mPowerLevel;

  public SuperHero() {
    mPowerLevel = 0;
  }

  public SuperHero(int powerLevel) {
    this.mPowerLevel= powerLevel;
  }

 
  protected void finalize() throws Throwable { 
    super.finalize();    
  }
}

class SuperHero {
  private int mPowerLevel;

  public SuperHero() {
     mPowerLevel = 0;
  }

  public SuperHero(int powerLevel) {
    this.mPowerLevel= powerLevel; 
  }

  ~SuperHero() {
   
  }
}

SuperHero hero = new SuperHero();

hero.setName("SpamMan");
hero.setPowerLevel(3);

hero.Defend("Laura Jones");
SuperHero.Rest();  

SuperHero hero2 = hero;   
hero2.setName("WormWoman");
System.out.println(hero.getName());  

hero = null;   

if (hero == null)
  hero = new SuperHero();

Object obj = new SuperHero();
System.out.println("object's type: " + obj.getClass().toString());
if (obj instanceof SuperHero)
  System.out.println("Is a SuperHero object.");

SuperHero hero = new SuperHero();

hero.Name = "SpamMan";
hero.PowerLevel = 3;

hero.Defend("Laura Jones");
SuperHero.Rest();  

SuperHero hero2 = hero;  
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name);  

hero = null ;  

if (hero == null)
  hero = new SuperHero();

Object obj = new SuperHero(); 
Console.WriteLine("object's type: " + obj.GetType().ToString());
if (obj is SuperHero)
  Console.WriteLine("Is a SuperHero object.");

private int mSize;

public int getSize() { return mSize; }
public void setSize(int value) {
  if (value < 0)
    mSize = 0;
  else
    mSize = value;
}


int s = shoe.getSize();
shoe.setSize(s+1);

private int mSize;

public int Size {
  get { return mSize; }
  set {
    if (value < 0)
      mSize = 0;
    else
      mSize = value;
  }
}

shoe.Size++;

No structs in Java.

struct StudentRecord {
  public string name;
  public float gpa;

  public StudentRecord(string name, float gpa) {
    this.name = name;
    this.gpa = gpa;
  }
}

StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;  

stu2.name = "Sue";
Console.WriteLine(stu.name);   
Console.WriteLine(stu2.name);  

java.io.DataInput in = new java.io.DataInputStream(System.in);
System.out.print("What is your name? ");
String name = in.readLine();
System.out.print("How old are you? ");
int age = Integer.parseInt(in.readLine());
System.out.println(name + " is " + age + " years old.");


int c = System.in.read();  
System.out.println(c);     


System.out.printf("The %s costs $%.2f for %d months.%n", "studio", 499.0, 3);


System.out.printf("Today is %tD\n", new java.util.Date());

Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age);
// or
Console.WriteLine(name + " is " + age + " years old.");

int c = Console.Read(); 
Console.WriteLine(c);   


Console.WriteLine("The {0} costs {1:C} for {2} months.\n", "studio", 499.0, 3);


Console.WriteLine("Today is " + DateTime.Now.ToShortDateString());

import java.io.*;


FileWriter writer = new FileWriter("c:\\myfile.txt");
writer.write("Out to file.\n");
writer.close();


FileReader reader = new FileReader("c:\\myfile.txt");
BufferedReader br = new BufferedReader(reader);
String line = br.readLine();
while (line != null) {
  System.out.println(line);
  line = br.readLine();
}
reader.close();


FileOutputStream out = new FileOutputStream("c:\\myfile.dat");
out.write("Text data".getBytes());
out.write(123);
out.close();


FileInputStream in = new FileInputStream("c:\\myfile.dat");
byte buff[] = new byte[9];
in.read(buff, 0, 9);   
String s = new String(buff);
int num = in.read();   
in.close();

using System.IO;


StreamWriter writer = File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();


StreamReader reader = File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
  Console.WriteLine(line);
  line = reader.ReadLine();
}
reader.Close();


BinaryWriter out = new BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
out.Write("Text data");
out.Write(123);
out.Close();


BinaryReader in = new BinaryReader(File.OpenRead("c:\\myfile.dat"));
string s = in.ReadString();
int num = in.ReadInt32();
in.Close();