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();
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebView2를 Visual Studio 2017 Express에서 사용할 수 있을 때까지Evergreen .Net Framework SDK 4.8 VisualStudio2017에서 NuGet을 사용하기 때문에 패키지 관리 방법을 packages.config 대신 PackageReference를 사용해야...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.