[c#] String과 같은 C # 기본 제공 유형을 확장하는 방법은 무엇입니까?

인사말 모든 사람이 … 내가 필요 . 그러나 문자열의 끝이나 시작 부분뿐만 아니라 문자열 자체에서 반복되는 모든 공백을 제거하고 싶습니다. 다음과 같은 방법으로 할 수 있습니다.TrimString

public static string ConvertWhitespacesToSingleSpaces(string value)
{
    value = Regex.Replace(value, @"\s+", " ");
}

내가 여기서 얻은 . 하지만이 코드 부분이 String.Trim()자체적 으로 호출되기를 원 하므로 Trim메서드 를 확장하거나 오버로드하거나 재정의해야한다고 생각합니다. 그렇게 할 수 있는 방법이 있습니까?

미리 감사드립니다.



답변

당신은 확장 할 수 없습니다 때문에 string.Trim(). 여기 에 설명 된대로 공백을 자르고 줄이는 Extension 메서드를 만들 수 있습니다.

namespace CustomExtensions
{
    //Extension methods must be defined in a static class
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static string TrimAndReduce(this string str)
        {
            return ConvertWhitespacesToSingleSpaces(str).Trim();
        }

        public static string ConvertWhitespacesToSingleSpaces(this string value)
        {
            return Regex.Replace(value, @"\s+", " ");
        }
    }
}

그렇게 사용할 수 있습니다

using CustomExtensions;

string text = "  I'm    wearing the   cheese.  It isn't wearing me!   ";
text = text.TrimAndReduce();

당신에게 준다

text = "I'm wearing the cheese. It isn't wearing me!";


답변

가능합니까? 예,하지만 확장 방법이있는 경우에만

클래스 System.String는 봉인되어 있으므로 재정의 또는 상속을 사용할 수 없습니다.

public static class MyStringExtensions
{
  public static string ConvertWhitespacesToSingleSpaces(this string value)
  {
    return Regex.Replace(value, @"\s+", " ");
  }
}

// usage: 
string s = "test   !";
s = s.ConvertWhitespacesToSingleSpaces();


답변

귀하의 질문에 예와 아니오가 있습니다.

예, 확장 메서드를 사용하여 기존 유형을 확장 할 수 있습니다. 확장 메서드는 당연히 유형의 공용 인터페이스에만 액세스 할 수 있습니다.

public static string ConvertWhitespacesToSingleSpaces(this string value) {...}

// some time later...
"hello world".ConvertWhitespacesToSingleSpaces()

아니요,이 메서드를 호출 할 수 없습니다 Trim(). 확장 메서드는 오버로딩에 참여하지 않습니다. 컴파일러가 이것을 자세히 설명하는 오류 메시지를 제공해야한다고 생각합니다.

확장 메서드는 메서드를 정의하는 형식이 포함 된 네임 스페이스가 using’ed 인 경우에만 표시됩니다.


답변

확장 방법!

public static class MyExtensions
{
    public static string ConvertWhitespacesToSingleSpaces(this string value)
    {
        return Regex.Replace(value, @"\s+", " ");
    }
}


답변

확장 방법을 사용하는 것 외에도 (여기서는 좋은 후보 일 가능성이 있음) 객체를 “포장”하는 것도 가능합니다 (예 : “객체 구성”). 래핑 된 양식에 래핑되는 것보다 더 많은 정보가 포함되지 않는 한 래핑 된 항목은 정보 손실없이 암시 적 또는 명시 적 변환을 통해 깔끔하게 전달 될 수 있습니다. 유형 / 인터페이스 만 변경하면됩니다.

즐거운 코딩입니다.


답변