Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
(시리즈 글이 18개 있습니다.)
.NET Framework: 1110. C# 11 - 인터페이스 내에 정적 추상 메서드 정의 가능 (DIM for Static Members)
; https://www.sysnet.pe.kr/2/0/12814

.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용
; https://www.sysnet.pe.kr/2/0/12839

.NET Framework: 1182. C# 11  - ref struct에 ref 필드를 허용
; https://www.sysnet.pe.kr/2/0/13015

.NET Framework: 2025. C# 11  - 원시 문자열 리터럴(raw string literals)
; https://www.sysnet.pe.kr/2/0/13085

.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지
; https://www.sysnet.pe.kr/2/0/13086

.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
; https://www.sysnet.pe.kr/2/0/13096

.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자
; https://www.sysnet.pe.kr/2/0/13099

.NET Framework: 2032. C# 11 - shift 연산자 재정의에 대한 제약 완화 (Relaxing Shift Operator)
; https://www.sysnet.pe.kr/2/0/13100

.NET Framework: 2035. C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift)
; https://www.sysnet.pe.kr/2/0/13110

.NET Framework: 2036. C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합
; https://www.sysnet.pe.kr/2/0/13111

.NET Framework: 2037. C# 11 - 목록 패턴(List patterns)
; https://www.sysnet.pe.kr/2/0/13112

.NET Framework: 2038. C# 11 - Span 타입에 대한 패턴 매칭 (Pattern matching on ReadOnlySpan<char>)
; https://www.sysnet.pe.kr/2/0/13113

.NET Framework: 2042. C# 11 - 파일 범위 내에서 유효한 타입 정의 (File-local types)
; https://www.sysnet.pe.kr/2/0/13117

.NET Framework: 2045. C# 11 - 메서드 매개 변수에 대한 nameof 지원
; https://www.sysnet.pe.kr/2/0/13122

.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
; https://www.sysnet.pe.kr/2/0/13123

.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
; https://www.sysnet.pe.kr/2/0/13125

.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
; https://www.sysnet.pe.kr/2/0/13126

.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
; https://www.sysnet.pe.kr/2/0/13276




C# 11 - 인터페이스 내에 정적 추상 메서드 정의 가능 (DIM for Static Members)

(2022-07-12 업데이트) 이 기능은 C# 11에 포함될 예정이고, .NET 7 환경을 필요로 합니다.




앞서 C# 8부터 기본 인터페이스 메서드가 추가되었습니다. 즉, 다음과 같이 인터페이스의 구현이 가능해졌고,

public interface IMessage
{
    public static int None = 0; // 정적 메서드/필드 가능

    public static int Any { get; } // 속성(및 이벤트)도 결국 메서드이므로.

    public void WriteLog(string text) => Console.WriteLine(text); // 인스턴스 메서드 가능
}

이를 지원하는 런타임은 (.NET Framework은 안 되고) .NET Core 3.0부터입니다.




그동안, 인터페이스는 내부에 명세한 "인스턴스 멤버"에 대해서는 하위 클래스에서 그것을 구현하도록 강제하는 것이 가능했습니다. 반면, 정적 메서드에 대해서는 이것이 불가능했는데요, 실제로 위의 코드에서 정적 속성 Any를 IMessage를 구현한 하위 클래스에서 구현 코드를 제공하도록 강제할 방법이 없습니다.

바로 이것을 지원하기 위해 새롭게 다음의 문법이 추가되었고,

Static abstract members in interfaces
; https://github.com/dotnet/csharplang/blob/main/proposals/static-abstracts-in-interfaces.md

따라서, 정적 메서드를 하위 클래스에서 구현하도록 abstract 예약어를 이용해 다음과 같이 강제할 수 있습니다.

public interface IMessage
{
    public static int None = 0;

    // C# 10 이전에는 컴파일 오류 발생
    // error CS0112: A static member 'IMessage<T>.Any' cannot be marked as override, virtual, or abstract
    public static abstract int Any { get; }

    static abstract void All();
}

public class Message : IMessage
{
    public static int Any => 5;

    public static void All()
    {
        Console.WriteLine("All called");
    }

    public Message()
    {
    }
}

즉, 이제는 인스턴스 메서드뿐만 아니라 정적 메서드까지도 하위 클래스에서의 구현을 강제할 수 있게 되었지만, 여기서 중요한 것은 그렇다고 해서 클래스 수준의 "다형성"이 제공되는 것은 아니라는 점입니다.

따라서, 사용 시에는 단순히 해당 정적 멤버가 구현된 클래스 이름을 특정해서 사용해야 합니다.

// 컴파일 오류 발생
// error CS8926: A static abstract interface member can be accessed only on a type parameter.
// Console.WriteLine(IMessage.Any);

Console.WriteLine(Message.Any);




사실, default interface method 정도는 자바로부터의,

// 자바 코드
interface ITest {
    public static int Version = 5;

    public default void Log() {
        System.out.println("Log");
    }
}

이식성을 높이기 위함이라는 정도로 이해해 줄 수 있습니다. 그런데, 추상 정적 메서드를 interface에 넣어 도대체 어디다 쓰려고 그러는 것일까요? ^^ 대개의 경우 이런 특이한 기능은, 마이크로소프트가 필요했다고 보면 됩니다. 실제로, 이것은 이전에 소개한 INumber<T>에서 사용하고 있습니다.

.NET 6 Preview 7에 추가된 숫자 형식에 대한 제네릭 연산 지원
; https://www.sysnet.pe.kr/2/0/12785

위의 글에 실어 놓았던 코드를 다시 보면,

public static T 합계<T>(this IEnumerable<T> arg) where T : INumber<T>
{
    T sum = T.Zero;

    foreach (T item in arg)
    {
        sum = sum + item;
    }

    return sum;
}

public static TResult 산술평균<T, TResult>(this IEnumerable<T> arg) where T : INumber<T>
    where TResult : INumber<TResult>
{
    return TResult.Create(arg.합계()) / TResult.Create(arg.Count());
}

바로 저 코드들이 INumber<T>의 abstract static 메서드였던 것입니다. 저렇게 보니, 정말 유용한 기능이긴 합니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




아래는 문서에 나온 몇 가지 메서드 유형을 예제로 나열한 것입니다.

interface IMy
{
    static abstract void M();
    static abstract IMy P { get; set; }
    static abstract event Action E;
    static abstract IMy operator +(IMy l, IMy r);
    static abstract bool operator ==(IMy l, IMy r);
    static abstract bool operator !=(IMy l, IMy r);

    // error CS0552: 'IMy.implicit operator IMy(string)': user-defined conversions to or from an interface are not allowed
    // static abstract implicit operator IMy(string s);

    // error CS0552: 'IMy.implicit operator string(IMy)': user-defined conversions to or from an interface are not allowed
    // static abstract implicit operator string(IMy s);

    static abstract bool operator !(IMy l);
}

interface IYour<T>
{
    static abstract void M();
    static abstract T P { get; set; }
    static abstract event Action E;

    // error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it.
    // static abstract T operator +(T l, T r);

    // error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it.
    // static abstract bool operator ==(T l, T r);

    // error CS8924: One of the parameters of a binary operator must be the containing type, or its type parameter constrained to it.
    // static abstract bool operator !=(T l, T r);

    // error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type
    // static abstract implicit operator T(string s);

    //  error CS8931: User-defined conversion in an interface must convert to or from a type parameter on the enclosing type constrained to the enclosing type
    // static abstract explicit operator string(T t);

    // error CS8921: The parameter of a unary operator must be the containing type, or its type parameter constrained to it.
    // static abstract bool operator !(T l);
}

interface ITheir<T> where T: ITheir<T>
{
    static abstract void M();
    static abstract T P { get; set; }
    static abstract T operator +(T l, T r);
    static abstract implicit operator T(string s);
    static abstract explicit operator string(T t);

    static abstract bool operator !(T l);
}

public class TheirClass : ITheir<TheirClass>
{
    public static TheirClass P { get => throw new NotImplementedException(); 
                                set => throw new NotImplementedException(); }

    public static void M() { }

    public static TheirClass operator +(TheirClass l, TheirClass r) => throw new NotImplementedException();
    public static implicit operator TheirClass(string s) => throw new NotImplementedException();
    public static explicit operator string(TheirClass t) => "type";
    public static bool operator !(TheirClass l) => true;
}

class YourClass<T> where T : ITheir<T>
{
    object Method()
    {
        return T.P;
    }
}




C# 11 - 인터페이스 내에 정적 추상 메서드 정의 가능(공식 문서, Static Abstract Members In Interfaces C# 10 Preview)
; https://www.sysnet.pe.kr/2/0/12814

C# 11 - 제네릭 타입의 특성 적용 (공식 문서, Generic attributes)
; https://www.sysnet.pe.kr/2/0/12839

C# 11 - 사용자 정의 checked 연산자 (공식 문서, Checked user-defined operators)
; https://www.sysnet.pe.kr/2/0/13099

C# 11 - shift 연산자 재정의에 대한 제약 완화 (공식 문서, Relaxing Shift Operator)
; https://www.sysnet.pe.kr/2/0/13100

C# 11 - IntPtr/UIntPtr과 nint/unint의 통합 (공식 문서, Numeric IntPtr)
; https://www.sysnet.pe.kr/2/0/13111

C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift) (공식 문서, Unsigned right shift operator)
; https://www.sysnet.pe.kr/2/0/13110

C# 11 - 원시 문자열 리터럴 (공식 문서, raw string literals)
; https://www.sysnet.pe.kr/2/0/13085

C# 11 - 문자열 보간 개선 2가지 (공식 문서, Allow new-lines in all interpolations)
; https://www.sysnet.pe.kr/2/0/13086

C# 11 - 목록 패턴 (공식 문서, List patterns)
; https://www.sysnet.pe.kr/2/0/13112

C# 11 - Span 타입에 대한 패턴 매칭 (공식 문서, Pattern matching on ReadOnlySpan<char>)
; https://www.sysnet.pe.kr/2/0/13113

C# 11 - Utf8 문자열 리터럴 지원 (공식 문서, Utf8 Strings Literals)
; https://www.sysnet.pe.kr/2/0/13096

C# 11 - ref struct에 ref 필드를 허용 (공식 문서, ref fields)
; https://www.sysnet.pe.kr/2/0/13015

C# 11 - 파일 범위 내에서 유효한 타입 정의 (공식 문서, File-local types)
; https://www.sysnet.pe.kr/2/0/13117

C# 11 - 메서드 매개 변수에 대한 nameof 지원 (공식 문서, nameof(parameter))
; https://www.sysnet.pe.kr/2/0/13122

C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가 (공식 문서, Required members)
; https://www.sysnet.pe.kr/2/0/13123

C# 11 - 구조체 필드의 자동 초기화 (공식 문서, auto-default structs)
; https://www.sysnet.pe.kr/2/0/13125

C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용 (공식 문서, Cache delegates for static method group)
; https://www.sysnet.pe.kr/2/0/13126

Language Feature Status
; https://github.com/dotnet/roslyn/blob/main/docs/Language%20Feature%20Status.md




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/5/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-09-23 11시18분
정성태
2023-04-10 01시11분
정성태

1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...
NoWriterDateCnt.TitleFile(s)
13247정성태2/7/20234962VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234085개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234627.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20233983VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234855디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234292디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233824디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20233982디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233625디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235632.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235320.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20234965개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234508개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235548개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20236897오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234698스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233614오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234030개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20234968.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235112.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234820개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234493.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233746개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234090Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234281오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20233932개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...