C\#연산 자 를 다시 불 러 옵 니 다.

본 고 는 연산 자 를 다시 싣 는 방법 을 비교적 상세 하 게 묘사 하 였 다.일반적으로 리 셋 연산 자 는 실제 프로젝트 개발 에 자주 사용 되 지만,일부 사용자 정의 유형 이 짧 은 몇 줄 코드 를 통 해 자주 사용 하 는 연산 자(예:+-*/)를 리 셋 하면 프로 그래 밍 작업 에 편 의 를 가 져 다 줄 수 있 습 니 다.다시 불 러 오 는 연산 자 는 컴 파일 러+-*/등 연산 자 에 게 사용자 정의 형식 에 대해 어떤 조작 을 하 는 지 알려 주 는 것 입 니 다.코드 에서 몇 가 지 를 주의해 야 합 니 다.
1.가능 한 한 연산 자 자체 의 의 미 를 바 꾸 지 마 세 요.
2.모든 연산 자 를 다시 불 러 오 려 면 Public 와 static 로 성명 해 야 합 니 다.
3.확장 방법 과 달리 다시 불 러 오 는 방법 은 다시 불 러 오 는 유형 내부 이 고 키워드 operator 를 사용 해 야 합 니 다.
C\#의 두 문자열 을 더 하면 실제 적 으로 두 문자열 을 연결 합 니 다.만약 에 두 개의 EmployeDetail 형식 을 더 하면 Employee Collection 집합 을 얻 을 수 있 습 니 다.예 를 들 어:

EmployeeDetail a,b;

....

EmployeeCollection collection = a+b;

컴 파일 러 가 위의 코드 를 만 났 을 때 EmployeDetail 류 에 operator+라 고 표 시 된 정적 방법 을 자동 으로 호출 하고 두 개의 연산 자 a 와 b 를 매개 변수 로 맞 는 방법 에 전달 합 니 다.이 방법 은 하나의 값 을 collection 에 부여 해 야 합 니 다.EmployeDetail 류 에 FirstName,MiddleName,LastName 이 세 가지 속성 이 있다 고 가정 합 니 다.이 세 개의 이름 을 연결 하 는 문자열 을 되 돌려 주 는 ToString 방법 도 다시 썼 습 니 다.코드 는 다음 과 같 습 니 다.

[Serializable]
 public class EmployeeDetail
 {
   public string FirstName { get; set; }
   public string MiddleName { get; set; }
   public string LastName { set;get; }
   public override string ToString()
   {
     return string.Format("{0}{1}{2}{3}{4}", FirstName, string.IsNullOrWhiteSpace(MiddleName) ? null : "."
       , MiddleName
       , string.IsNullOrWhiteSpace(LastName) ? null : ".",
       LastName).Trim();
   }
 }
다음 코드 는"+"연산 자 에 지원 하 는 연산 자 를 다시 불 러 옵 니 다.

public static EmployeeCollection operator +(EmployeeDetail a, EmployeeDetail b)
{
  return new EmployeeCollection() { a, b };
}

OK,EmployeDetail 류 에 이런 방법 을 더 하면 우 리 는 아래 의 코드 를 쓸 수 있 습 니 다.

EmployeeCollection collection = new EmployeeDetail(){FirstName="Jackson",LastName="Bruce"} + new EmployeeDetail(){FirstName="Michael",LastName="Jackson"} ;

그러나 이것 은 완벽 하지 않 습 니 다.a,b,c 가 모두 EmployeDetail 형식 이 라 고 가정 하면 다음 코드 는 컴 파일 오 류 를 던 집 니 다.

EmployeeCollection collection = a + b + c;

왜 컴 파일 이 통과 되 지 않 습 니까?할당 연산 자 를 제외 한 표현 식 은 왼쪽 에서 오른쪽으로 실 행 됩 니 다.a+b 는 EmployeCollection 형식 으로 되 돌아 갑 니 다.EmployeCollection 유형 은'+'연산 자 를 다시 불 러 오지 않 았 습 니 다.컴 파일 러 는 어떤 조작 을 수행 해 야 할 지 모 르 기 때문에 우 리 는 다음 과 같은 두 가지 방법 이 있 습 니 다.

public static EmployeeCollection operator +(EmployeeCollection collection, EmployeeDetail a)
{
  collection.Add(a);
  return collection;
}
public static EmployeeCollection operator +(EmployeeDetail a, EmployeeCollection collection)
{
  return collection + a;
}

완벽 해 보이 지만 더 잘 할 수 있 습 니 다.예 를 들 어 문자열'Jackson.Bruce'를 EmployeDetail 형식 으로 직접 암시 적 으로 바 꾸 려 면'Jackson.Bruce'와 같은 형식의 문자열 을 EmployeDetail 유형의 대상 에 직접 부여 할 수 있 습 니 다.예 를 들 어 EmployeDetail employee='Jackson.Bruce'등 입 니 다.그러면 은 식 형식 변환 연산 자 를 다시 불 러 와 야 합 니 다.코드 는 다음 과 같 습 니 다.

/// <summary>
///       
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static implicit operator EmployeeDetail(string name)
{
       ///                  name          ,          
       ///
  string[] arr;
  return string.IsNullOrWhiteSpace(name) ? null :
 new EmployeeDetail()
 {
   FirstName = (arr = name.Trim().Split('.'))[0]
   ,
   LastName = arr.Length > 1 ? arr[arr.Length > 2 ? 2 : 1] : null,
   MiddleName = arr.Length > 2 ? arr[1] : null
 };
}
public static EmployeeCollection operator +(EmployeeDetail a, string b)
{
  return new EmployeeCollection() { a, b };
}

여기 서 당신 은 잠시 도 지체 하지 않 고 시험 해 보고 싶 습 니까?OK 콘 솔 프로그램 을 써 서 테스트 해 보 세 요.

static void Main(string[] args)
{
  EmployeeDetail employee = "Jackson.Bruce";
  Console.WriteLine("FirstName={0},MiddleNam={1},LastName={2}", employee.FirstName, employee.MiddleName, employee.LastName);
  Console.WriteLine("toString={0}", employee);
  Console.WriteLine();

  EmployeeCollection collection = "Michael.Jackson" + employee;

  collection += "Bruce.Lee";
  foreach (var e in collection)
  {
 Console.WriteLine(e);
  }
  Console.WriteLine();

  collection -= employee;

  foreach (var e in collection)
  {
 Console.WriteLine(e);
  }
  Console.WriteLine("===end===");
  Console.Read();
}

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

모든 코드 에는 다른 연산 자의 과부하 도 포함 되 어 있 습 니 다.여 기 는 더 이상 소개 하지 않 겠 습 니 다.어서 테스트 해 보 세 요.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace      
{
  [Serializable]
  public class EmployeeDetail
  {
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { set;get; }
    public static EmployeeCollection operator +(EmployeeDetail a, EmployeeDetail b)
    {
      return new EmployeeCollection() { a, b };
    }

   
    
    public static EmployeeCollection operator +(EmployeeCollection collection, EmployeeDetail a)
    {
      collection.Add(a);
      return collection;
    }
    public static EmployeeCollection operator +(EmployeeDetail a, EmployeeCollection collection)
    {
      return collection + a;
    }
    /// <summary>
    ///       
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static implicit operator EmployeeDetail(string name)
    {
      string[] arr;
      return string.IsNullOrWhiteSpace(name) ? null :
        new EmployeeDetail()
        {
          FirstName = (arr = name.Trim().Split('.'))[0]
          ,
          LastName = arr.Length > 1 ? arr[arr.Length > 2 ? 2 : 1] : null,
          MiddleName = arr.Length > 2 ? arr[1] : null
        };
    }
    public static EmployeeCollection operator +(EmployeeDetail a, string b)
    {
      return new EmployeeCollection() { a, b };
    }
    public override string ToString()
    {
      return string.Format("{0}{1}{2}{3}{4}", FirstName, string.IsNullOrWhiteSpace(MiddleName) ? null : "."
        , MiddleName
        , string.IsNullOrWhiteSpace(LastName) ? null : ".",
        LastName).Trim();
    }
  }
  public class EmployeeCollection : List<EmployeeDetail>
  {
    public static EmployeeCollection operator +(EmployeeCollection a, string b)
    {
      a.Add(b);
      return a;
    }
    public static EmployeeCollection operator +(string b, EmployeeCollection a)
    {
      return a + b;
    }

    public static EmployeeCollection operator -(EmployeeCollection a, EmployeeDetail b)
    {
      a.Remove(b);
      return a;
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      EmployeeDetail employee = "Jackson.Bruce";
      Console.WriteLine("FirstName={0},MiddleNam={1},LastName={2}", employee.FirstName, employee.MiddleName, employee.LastName);
      Console.WriteLine("toString={0}", employee);
      Console.WriteLine();

      EmployeeCollection collection = "Michael.Jackson" + employee;

      collection += "Bruce.Lee";
      foreach (var e in collection)
      {
        Console.WriteLine(e);
      }
      Console.WriteLine();

      collection -= employee;

      foreach (var e in collection)
      {
        Console.WriteLine(e);
      }


      Console.WriteLine("===end===");
      Console.Read();
    }
  }
}

좋은 웹페이지 즐겨찾기