日期:2014-05-19  浏览次数:20709 次

关于this以及静态成员的问题?
刚刚开始学C#,以下的程序有点搞不明白
请高手帮帮忙!

using   System;
class   Test
{
int   x;
static   int   y;
  void   F(){
      x=1;//正确,等价于this.x=1
      y=1;//正确,等价于Test.y=1
}
    static   void   G(){
      x=1;//错误,不能访问this.x
      y=1;//正确,等价于Test.y=1
}
    static   void   Main(){
      Test   t=new   Test();
      t.x=1;//正确
      t.y=1;//错误,不能在类的实例中访问静态成员
      Test.x=1;//错误,不能按类访问非静态成员
      Test.y=1;//正确
  }
}

等价于this.x=1和等价于Test.y=1的区别?不明白这两句有什么不一样的

------解决方案--------------------
this 是一个保留字,仅限于构造函数和方法成员中使用
在类的构造函数中出现表示对正在构造的对象本身的引用,在类的方法中出现表示对调用该方法的对象的引用,在结构的构造上函数中出现表示对正在构造的结构的引用,在结构的方法中出现表示对调用该方法的结果的引用
this 保留字不能用于静态成员的实现里,因为这时对象或结构并未实例化
在 C# 系统中,this 实际上是一个常量,所以不能使用 this++ 这样的运算
this 保留字一般用于限定同名的隐藏成员、将对象本身做为参数、声明索引访问器、判断传入参数的对象是否为本身

示例:
using System;
using System.Collections.Generic;
using System.Text;
namespace Example10
{
class Class1
{
private double c;
private string value;
public double C
{
get
{
return c;
}
}
public Class1(double c)
{
//限定同名的隐藏成员
this.c = c;
}
public Class1(Class1 value)
{
//用对象本身实例化自己没有意义
if (this != value)
{
c = value.C;
}
}
public override string ToString()
{
//将对象本身做为参数
return string.Format( "{0} Celsius = {1} Fahrenheit ", c, UnitTransClass.C2F(this));
}

//由于好奇,在这做了一个效率测试,想看看到底哪种方式访问成员变量更快,结论:区别不大。。。
public string Test1()
{
long vTickCount = Environment.TickCount;
for (int i = 0; i < 10000000; i++)
this.value = i.ToString();
return string.Format( "Have this.: {0} MSEL ", Environment.TickCount - vTickCount);
}
public string Test2()
{
long vTickCount = Environment.TickCount;
for (int i = 0; i < 10000000; i++)
value = i.ToString();
return string.Format( "Don 't have this.: {0} MSEL ", Environment.TickCount - vTickCount);
}
}
class UnitTransClass
{
public static double C2F(Class1 value)
{
//摄氏到华氏的转换公式
return 1.8 * value.C + 32;
}
}
class Program
{
static void Main(string[] args)
{
Class1 tmpObj = new Class1(37.5);
Console.WriteLine(tmpObj);
Console.WriteLine(tmpObj.Test1());
Console.WriteLine(tmpObj.Test2());
Console.ReadLine();
}
}
}
结果:
37.5 Celsius = 99.5 Fahrenheit
Have this.: 4375 MSEL
Don 't have this.: 4406 MSEL