// keywords_this.cs
// this example
using System;
class Employee
{
private string name;
private string alias;
private decimal salary = 3000.00m; // Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
} // Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
} public decimal Salary
{
get { return salary; }
}
}
class Tax
{
public static decimal CalcTax(Employee E) //这里的(Employee E )是什么意思?是实例化还是
//作/参传递,求详细解答
{
return 0.08m * E.Salary;
}
}class MainClass
{
static void Main()
{
// Create objects:
Employee E1 = new Employee("John M. Trainer", "jtrainer"); // Display results:
E1.printEmployee();
}
}
/*运行结果:Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00*/
C#
// this example
using System;
class Employee
{
private string name;
private string alias;
private decimal salary = 3000.00m; // Constructor:
public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
} // Printing method:
public void printEmployee()
{
Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
// Passing the object to the CalcTax method by using this:
Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
} public decimal Salary
{
get { return salary; }
}
}
class Tax
{
public static decimal CalcTax(Employee E) //这里的(Employee E )是什么意思?是实例化还是
//作/参传递,求详细解答
{
return 0.08m * E.Salary;
}
}class MainClass
{
static void Main()
{
// Create objects:
Employee E1 = new Employee("John M. Trainer", "jtrainer"); // Display results:
E1.printEmployee();
}
}
/*运行结果:Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00*/
C#
{
static void Main(string[] args)
{
Employee myE = new Employee() { id=4};
Console.WriteLine("初始化为:"+myE.id);
testMethod(myE);
Console.WriteLine("退出方法后:"+myE.id);
Console.ReadLine();
}
static void testMethod(Employee myE)
{
//myE.id = 5;
myE = new Employee() { id = 5 }; //此处是什么原理呢???
Console.WriteLine("更改为:"+myE.id);
}
}
class Employee
{
public int id { get; set; }
}
C# 3.0新写法
相当于
myE = new Employee();
myE.id = 5;
public static decimal CalcTax(Employee E)
这句话中 public是方法的访问权限;
static表示方法为静态方法;
decimal表示调用这个方法返回一个decimal类型的返回值;
CalcTax是方法的名字;
Employee是调用这个方法所需的第一个参数的参数类型;
E表示这个参数在方法中用E 来代表;
所以“Employee E” 其实就是 :调用“CalcTax”这个方法的时候 这个方法需要一个“Employee“类型的值,这个值在方法里用E来代表参与运算
第二个是实例化的时候直接赋值