C#和Javascript相似性比较

1         语法基本一样

两者都是C系语言。

2         对象构造:

2.1       javascript:

var obj = {Name:”sfeig”,Age:31};

2.2       C#:                   

var obj = new {Name=”sfeig”,Age=23};

3         数组:

3.1       javascript:     

var arr = [1, 2, 3, 4, 5];

3.2       C#:       

var arr = new [] {1,2,3,4,5};

4         匿名函数:

4.1       javascript:

var handler = function(sender,e){…};

4.2       C#:       

var handler = delegate(object sender,EventArgs e){….};

5         扩展方法:

5.1       Javascript

function Vector(x,y)

{     

    this.x = x;     

    this.y = y;

}

 

Vector.prototype.adds = function(v)

{    

    if(v instanceof Vector)     

    {               

        return new Vector(this.x+v.x, this.y + v.y);      

    }      

    else      

    {              

        alert("Invalid Vector object!");     

    }

}

 

 

var v = new Vector(1,2);

v = v.adds(v);

alert("x = " +v.x + ", y = "+v.y);

5.2       C#:

public class Vector

{

    private double _x;

    private double _y;

 

    public double X

    {

        get { return this._x; }

        set { this._x = value; }

    }

 

    public double Y

    {

        get { return this._y; }

        set { this._y = value; }

    }

}

 

public static class Extension

{

    public static Vector Adds(this Vector p, Vector p1)

    {

        return new Vector { X = p.X + p1.X, Y = p.Y + p1.Y };

    }

}

 

var v = new Vector { X = 1, Y = 2 };

v = v.Adds(v);

Console.WriteLine("v.X = {0} and v.Y = {1}", v.X, v.Y);

6         null赋值:

6.1       C#中:

//string str = "hello";

string str = null;

this.Label1.Text = str ?? "china";

6.2       Javascript中:

var s0 = null;

//var s0 = "hello";

var s = s0 || "china";

alert(s);

原文地址:https://www.cnblogs.com/AndyGe/p/1590354.html