C\#에서 this 의 사용 사례 분석

2924 단어 C#this
this 키 워드 는 C\#프로 그래 밍 에서 의 응용 이 매우 빈번 합 니 다.오늘 본 고 는 this 키워드 의 용법 에 대해 분석 을 하고 여러분 의 C\#프로 그래 밍 에 어느 정도 도움 이 되 기 를 바 랍 니 다.구체 적 인 분석 은 다음 과 같다.
1.현재 클래스 를 대표 합 니 다.현재 클래스 에서 this 를 사용 하여 현재 클래스 의 구성원 변수 와 방법 을 방문 할 수 있 습 니 다(주의해 야 할 것 은 정적 방법 에서 this 를 사용 할 수 없습니다).또한 매개 변수 전달 에 사용 하여 현재 대상 의 인용 을 전달 할 수 있 습 니 다.
예제 코드 는 다음 과 같다.

class Program
{
  static void Main(string[] args)
  {
    thisClass testObj = new thisClass();
    Console.ReadLine();
  }
}
class thisClass
{
  private string A { get; set; }
  public thisClass()
  {
    /*   this       A         A  */
    this.A = "Test String";
    Console.WriteLine(this.TestFun("TestFun :"));
  }
  private string TestFun(string args)
  {
    return args + this.A;
  }
}

실행 결 과 는 다음 그림 과 같 습 니 다.

2.성명 색인 기
색인 기:클래스 와 구조의 인 스 턴 스 를 배열 과 같은 방식 으로 색인 할 수 있 습 니 다.색인 기 는 속성 과 유사 합 니 다.다른 점 은 방문 기 가 파 라 메 터 를 사용 하여 파 라 메 터 를 사용 하 는 것 입 니 다.파 라 메 트릭 속성 이 라 고 불 립 니 다.색인 은 다시 불 러 올 수 있 고 인 스 턴 스 구성원 에 속 하 며 static 라 고 밝 힐 수 없습니다.
예제 코드 는 다음 과 같다.

class Program
{
  static void Main(string[] args)
  {
    indexClass intIndexClass = new indexClass();
    intIndexClass[0] = new thisClass("intIndexClass 111");
    intIndexClass[1] = new thisClass("intIndexClass 222");
    indexClass stringIndexClass = new indexClass();
    stringIndexClass["string1"] = new thisClass("stringIndexClass string1");
    stringIndexClass["string2"] = new thisClass("stringIndexClass string2");
    Console.ReadLine();
  }
}
class indexClass
{
  /*    */
  private thisClass[] thisClassArr = new thisClass[10];
  private Hashtable thisClassStrArr = new Hashtable();
  /*     1        ,      ,     static*/
  public thisClass this[int index]
  {
    get { return thisClassArr[index]; }
    set { this.thisClassArr[index] = value; }
  }
  /*     2*/
  public thisClass this[string index]
  {
    get
    {
      return thisClassStrArr[index] as thisClass;
    }
    set { this.thisClassStrArr[index] = value; }
  }
}
class thisClass
{
  private string A { get; set; }
  public thisClass(string str)
  {
    /*   this       A         A  */
    this.A = str;
    Console.WriteLine(this.TestFun("TestFun :"));
  }
  private string TestFun(string args)
  {
    return args + this.A;
  }
}

실행 결 과 는 다음 그림 과 같 습 니 다.

좋은 웹페이지 즐겨찾기