CSharp Similarities and Differences

This document lists some basic differences between Nemerle and C# in a terse form. If you know Java or C++ it should still be fairly helpful.

Changes In Expressions

C# Nemerle Remarks
const int x = 3;
const string y = "foo";
readonly Object obj = getObject();
def x : int = 3;
def y : string = "foo";
def obj : Object = getObject();
Variables defined with def cannot be changed once defined. This is similar to readonlyor const in C# orfinal in Java. Most variables in Nemerle aren‘t explicitly typed like this.
int x = 3;
string y = "foo";
Object obj = getObject();
mutable x : int = 3;
mutable y : string = "foo";
mutable obj : Object = getObject();
Variables defined with mutable can be changed once defined. Most variables in Nemerle aren‘t explicitly typed like this.
var = 3; //Will compile.
var y; y = "foo";//Won‘t compile.
def = 3;//Will compile!
mutable y; y = "foo";//Will compile!
Nemerle‘s type inference is lightyears ahead of C#‘s. If there is clear evidence of a variable‘s type, there‘s a 99% chance Nemerle will infer it.
int a = b = c;
def a = c;
def b = c;
The type of the assignment operator is void.
value = cond ? var1 : var2;
value = if(cond) var1 else var2
No ternary operator is needed as everything is an expression in Nemerle. The ‘else‘ branch is mandatory here! (Don‘t panic! if-without-else has its own keyword.)
Class myClass = new Class(parms);
def myClass = Class(parms);
Nemerle doesn‘t require new when calling a constructor.
Book[] books = new Book[size];
def books = array(size) : array[Book];
Often the array type can be inferred and this is simplified; as in the next example.
Book[] books = new Book[size];
books[0] = new Book();
def books = array(size);
books[0] = Book();
When the type can be inferred from context or later use (which is most of the time), you can drop the type declaration
int[] numbers = {1, 2, 3};
def numbers = array[1, 2, 3];
Initializing an array. Without the arraykeyword this would create a list.
int[,] numbers = new int[2,3];
def numbers = array(2,3) : array.[2][int];
Multidimensional array constructor. The type can usually be inferred from use and not declared.
int[,] numbers = { {1,2,3}, {1,4,9} };
def numbers = [ [1,2,3], [1,4,9] ];
Multidimensional array initialization.
new {Prop1 = 1; Prop2 = "string"}
using Nemerle.Extensions;
new (Prop1 = 1, Prop2 = "string")
Nemerle anonymous typesare a bit more flexible (e. g. can be generic or returned from a method). They must be imported from Nemerle.Extensions however.
new Class {
  Property1 = 1;
  Property2 = "string"
}
Class()
The Nemerle Object Modifier macro is more powerful.
if(cond)
  answer = 42;
...
when(cond)
  answer = 42;
...
if without else is called when. Nemerle requiresif statements to be paired with elsefor clarity.
if(!cond)
  answer = 42;
...
unless(cond)
  answer = 42;
...
In Nemerle,if(!cond) can use the clearerunless(cond)syntax. Of course,when(!cond) can also always be used.
if (cond)
  return foo;
do_something ();
return bar;
match(cond){
| true => foo
| _ => {doSomething(); foo}
}
Pattern Matchingprovides a clearer way of delegating control flow.
if (cond)
  return foo;
do_something ();
return bar;
using Nemerle.Imperative;
when(cond)
  return foo
do_something ();
return bar;
Alternately the Imperative namespace may be imported. This isdiscouragedhowever.
try {...}
catch (FooException e) { ... }
catch (BarException e) { ... }
try {...}
catch {
  | e is FooException => ...
  | e is BarException => ...
}
Nemerle‘s somewhat differenttry ... catchsyntax is consistent with its pattern matching syntax.
(type) expr
expr :> type
Runtime type cast, allows for downcasts and upcasts.
(type) expr
expr : type
Static cast, only upcasts are allowed.
using System;
using SWF = System.Windows.Forms;
using System.Xml;
...
Console.WriteLine ("foo");
SWF.Form x = new SWF.Form();
XmlDocument doc = new XmlDocument();
using System;
using System.Console;
using SWF = System.Windows.Forms;
...
WriteLine("foo");
def x = SWF.Form();
def doc = Xml.XmlDocument();
In Nemerle, you can apply the usingdirective to classes as well as namespaces. Opened namespaces allow you to drop the prefix of other namespaces, likeSystem inSystem.XmlMore info.
using System.Windows.Forms;

Button button = control as Button;

if (button != null)
  ...
else
  ...
match (control) {
  | button is Button => ...
  | listv is ListView => ...
  | _ => ...//something else
}
as can be simulated withmatch. It is a bit more to type up in simple cases, but in general Nemerle‘s construct is more powerful.
int y = x++;
++x;
def y = x;
x++;
++x;
The ++ and -- operators return void, just like assignment. So, both prefix and postfix versions are equivalent.

Changes In Type Definitions

C# Nemerle Remarks
static int foo (int x, string y)
{ ... }
static foo (x : int, y : string) : int
{ ... }
Types are written after variable names.
class Foo {
  public Foo (int x)
  { ... }
}
class Foo {
  public this (x : int)
  { ... }
}
The constructor‘s name is alwaysthis.
class Foo {
  ~Foo ()
  { ... }
}
class Foo {
  protected override Finalize () : void
  { ... }
}
There is no special syntax for the destructor, you just override theFinalizemethod.
class Foo : Bar {
  public Foo (int x) : base (x)
  { ... }
}
class Foo : Bar {
  public this (x : int) {
    base (x);
    ...
  }
}
The base constructor is called in the constructor‘s function body.
class Foo {
  int x;
}
class Foo {
  mutable x : int;
}
Fields which will be changed outside of the constructor need to be marked asmutable.
class Foo {
  readonly int x;
  const int y = 10;
}
class Foo {
  x : int;
  y : int = 10;
}
Read-only/const are used by default.
class Foo {
  static int x = 1;
}
class Foo {
  static mutable x : int = 1;
}
Static variable.
class Foo {
  static readonly int x;
  static int method() { ... }
}
module Foo {
  x : int;
  method() : int { ... }
}
A module is a class in which all members are static.
using System.Runtime.CompilerServices.CSharp;

class C {
  public object this [int i]
  { ... }

  [IndexerName("MyItem")]
  public int this [string name]
  { ... }
}
class C {
  public Item [i : int] : object
  { ... }

  public MyItem [name : string] : int
  { ... }
}
Indexers.
C# Nemerle
When two interfaces use the same method to perform different functions, different names can be given to each method.
interface SpeaksEnglish{
    void Speak();
}

interface SpeaksGerman{
    void Speak();
}

class GermanTransfer : SpeaksEnglish, SpeaksGerman{
    public void SpeaksEnglish.Speak() {}
    public void SpeaksGerman.Speak() {}
}
interface SpeaksEnglish{
    Speak() : void;
}

interface SpeaksGerman{
    Speak() : void;
}

class GermanTransfer : SpeaksEnglish, SpeaksGerman{
    public Speak() : void implements SpeaksEnglish.Speak{}
    public Sprechen() : void implements SpeaksGerman.Speak{}
}

Generics

C# Nemerle Remarks
class A  { T x; }
class A [T] { x : T; }
Type parameters are written in square brackets [...].
typeof(A);
typeof(A[_,_]);
typeof expression

New Stuff

Nemerle contains many constructs which are not present in C#. Unfortunately, most of them don‘t really fit into a side-by-side comparison format:

Other Minor Differences

Ambiguity Isn‘t Tolerated

namespace YourAttributes{
    class Serializable : System.Attribute { }
}
namespace MyAttributes{
    using YourAttributes;
    class Serializable : System.Attribute { }

    [Serializable] class SomeClass { }
}

C# compilers will choose MyAttributes.Serializable or, if its definition is commented out, YourAttributes.Serializable. Nemerle will raise an error telling you to be more specific about which attribute you want to use.

Exclusion of Overridden Methods

 class BaseClass
 {
   public virtual AddItem (val : string) :  void { }
 }

 class TestClass : BaseClass
 {
   public AddItem (val : object) :  void { }
   public override AddItem (val : string) :  void { }
 }
 ...
   TestClass().AddItem ("a");  // C# will choose TestClass.AddItem (object)
                               // Nemerle will choose TestClass.AddItem (string)

This behaviour comes from section 7.6.5.1 of the C# specification, which states "...methods in a base class are not candidates [for overload resolution] if any method in a derived class is applicable (§7.6.5.1)." Unfortunately, this rule is patently absurd in situations like the above. The Nemerle compiler always chooses the method whose signature best matches the given arguments.

时间: 2024-08-06 02:13:27

CSharp Similarities and Differences的相关文章

The Similarities and Differences Between C# and Java -- Part 1(译)

原文地址 目录 介绍(Introduction) 相似点(Similarities) 编译单位(Compiled Units) 命名空间(Namespaces) 顶层成员(类型)(Top Level Elements(Types)) 基础类型(Basic Types) 类(Classes) 结构体(Structures) 接口(Interfaces) 泛型(Generic Types) 委托(Delegates) 枚举(Enumerations) 类型访问级别(Type Visibilities

【云迁移论文笔记】Cloud Migration Research:A Systematic Review

Cloud Migration Research:A Systematic Review Author Info: Pooyan Jamshidi PhD Postdoctoral Researcher Dublin City University· School of Computing Major: model-driven software architecture evolution PS: This paper is the first SLR(Systematic Literatur

A tutorial on Principal Components Analysis | 主成分分析(PCA)教程

A tutorial on Principal Components Analysis 原著:Lindsay I Smith, A tutorial on Principal Components Analysis, February 26, 2002. 翻译:houchaoqun.时间:2017/01/18.出处:http://blog.csdn.net/houchaoqun_xmu  |  http://blog.csdn.net/Houchaoqun_XMU/article/details

A Brief Review of Supervised Learning

There are a number of algorithms that are typically used for system identification, adaptive control, adaptive signal processing, and machine learning. These algorithms all have particular similarities and differences. However, they all need to proce

What Great .NET Developers Ought To Know (More .NET Interview Questions)

A while back, I posted a list of ASP.NET Interview Questions. Conventional wisdom was split, with about half the folks saying I was nuts and that it was a list of trivia. The others said basically "Ya, those are good. I'd probably have to look a few

Streaming Big Data: Storm, Spark and Samza--转载

原文地址:http://www.javacodegeeks.com/2015/02/streaming-big-data-storm-spark-samza.html There are a number of distributed computation systems that can process Big Data in real time or near-real time. This article will start with a short description of th

枯草芽孢杆菌bacillus subtilis

枯草杆菌,学名为枯草芽孢杆菌(Bacillus subtilis),属于芽孢杆菌属(Bacillus)为革兰氏阳性菌,是一种好气性菌,普遍存在于土壤及植物体表,在人体亦可发现在肠道内共生的枯草杆菌.型态上的主要特征是菌体表面生有鞭毛,体内形成的内生孢子可抵抗恶劣的外在环境而存活.最近的研究显示,枯草杆菌其实并不全然是好气性的.枯草杆菌在食品和饲料添加剂上广范使用,近年来使用在种子保护及生物防治上,也经常被拿来应用.临床医学上是属于安全性的有益微生物. 枯草芽胞杆菌,是芽胞杆菌属的一种.单个细胞0

Learning JavaScript Design Patterns -- A book by Addy Osmani

Learning JavaScript Design Patterns A book by Addy Osmani Volume 1.6.2 Tweet Copyright © Addy Osmani 2015. Learning JavaScript Design Patterns is released under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 unported license. It

TIJ英文原版书籍阅读之旅——Chapter One:Introduction to Objects

///:~容我对这个系列美其名曰“读书笔记”,其实shi在练习英文哈:-) Introduction to Objects Object-oriented programming(OOP) is part of this movement toward using the computer as an expressive medium. This chapter will introduce you to the basic concepts of OOP, including an over