Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 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 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가

개체 생성 시에 반드시 초기화를 강제할 수 있는 옵션이 C# 11부터 required라는 예약어를 통해 제공됩니다.

public class Person
{
    public required int Age;

    public required string FirstName { get; init; }
    public string MiddleName { get; init; } = "";
    public required string LastName { get; init; }
}

public class Employee
{
    public required int Age;

    public string Name { get; init; }

    public Employee(string name)
    {
        this.Name = name;
    }
}

위와 같이 정의한 타입은 이제 다음과 같은 식으로 required 멤버 초기화를 빼먹지 말고 "개체 초기화 구문"과 함께 new를 해야 합니다.

Person p = new Person { Age = 62, FirstName = "Anders", LastName = "Hejlsberg" };

Employee e = new Employee("Anders") { Age = 62 };

// 하나라도 빼먹으면, 컴파일 에러: error CS9035: Required member 'Person.Age' must be set in the object initializer or attribute constructor.
Person p1 = new Person { FirstName = "Anders", LastName = "Hejlsberg" };

개체 초기화에 사용하려면 당연히 외부에서 접근이 가능해야 하므로 required 멤버는 그것을 소유한 class의 접근성을 만족해야 합니다.

internal class Employee 
{ 
    internal required int Age;
    // ..
}

즉, class는 public인데, required 멤버가 internal 이하의 접근성을 가진다면 이런 식의 오류 메시지가 발생합니다.

error CS9032: Required member 'Employee.Age' cannot be less visible or have a setter less visible than the containing type 'Employee'.

재미있는 것은, required 필드가 개체 초기화 구문을 통해서만 값을 설정해야 유효하다는 점입니다. 가령, Employee 타입의 생성자에 required 필드 값을 초기화한다면,

// 컴파일 오류: error CS9035: Required member 'Employee.Age' must be set in the object initializer or attribute constructor.
Employee e = new Employee("Anders");
Employee e = new Employee("Anders", 62);

public class Employee
{
    public required int Age;

    public string Name { get; init; }

    public Employee(string name)
    {
        this.Name = name;
        this.Age = 0;
    }

    /* 또는, 생성자에 값을 전달하도록 제공해도, */

    public Employee(string name, int age)
    {
        this.Name = name;
        this.Age = age;
    }
}

그래도 컴파일 오류가 발생합니다. 이건 좀 그렇죠? required에 해당하는 멤버를 생성자에서 초기화했으면 C# 컴파일러가 인식해서 넘어가도 좋을 듯한데, 아쉽게도 그걸 허용하지 않는 겁니다. 이럴 때 개발자가 직접 해당 생성자에서는 required 멤버를 모두 초기화한 것으로 가정하라고 컴파일러에게 SetsRequiredMembers라는 특성을 지정해 통과하는 방법이 있습니다.

// 정상적으로 컴파일
Employee e = new Employee("Anders");

public class Employee
{
    // ... Age, Name 멤버 ...

    [SetsRequiredMembers]
    public Employee(string name)
    {
        this.Name = name;
        this.Age = 0;
    }
}

또한, SetsRequiredMembers 특성이 부여된 생성자는 required 멤버를 꼭 초기화하지 않아도 됩니다.

// 그래도 정상적으로 컴파일
Employee e = new Employee("Anders");

public class Employee
{
    // ... Age, Name 멤버 ...

    [SetsRequiredMembers]
    public Employee(string name)
    {
        this.Name = name;
    }
}




자, 그럼 이런 특징이 클래스 상속으로 넘어오면 어떻게 될까요? Employee를 이렇게 정의한 경우,

public class Employee
{
    public required int Age;

    public string Name { get; init; }

    public Employee(string name)
    {
        this.Name = name;
    }
}

상속을 해도 특별히 달라지는 점은 없습니다.

public class Salesman : Employee
{
    public Salesman(string name) : base(name) { }
}

어차피 base 클래스의 required 멤버가 public이므로 하위 클래스를 사용할 때도 개체 초기화 구문을 사용해 정의하는 것이 가능하기 때문입니다.

Salesman s = new Salesman("Mark") { Age = 30 };

단지, 부모 클래스의 생성자를 연계하는 경우라면 SetsRequiredMembers도 상속 클래스의 생성자에서 지정해야 한다는 정도만 알아두시면 되겠습니다.

public class Salesman : Employee
{
    // 연동하려는 부모 클래스의 생성자가 SetsRequiredMembers 특성을 지정했으므로!
    // 만약 자식 클래스에서 지정하지 않으면 "CS9039 This constructor must add 'SetsRequiredMembers' because it chains to a constructor that has that attribute." 컴파일 오류
    [SetsRequiredMembers]
    public Salesman(string name) : base(name)
    {
    }
}

public class Employee
{
    public required int Age;

    public string Name { get; init; }

    [SetsRequiredMembers]
    public Employee(string name)
    {
        this.Name = name;
    }
}




기타 제약이라면, required 멤버는 class, struct, record에서만 허용되고 interface에는 정의할 수 없습니다.

public interface IEmployee
{
    // error CS0106: The modifier 'required' is not valid for this item
    required int Age { get; }
}

또한, 다음의 예약어가 적용된 멤버는 required를 조합해 적용할 수 없습니다.

  • fixed
  • ref readonly
  • ref
  • const
  • static

마지막으로, (굳이 언급해야 할 필요가 있을까 싶지만) property 정의 구문과 유사한 indexer의 경우에도 그 특성상 required를 적용할 수 없습니다.

public class Number
{
    // 컴파일 오류: error CS0106: The modifier 'required' is not valid for this item
    public required int this[int i] { get { return i; } }
}




참고로, C# 컴파일러는 required 멤버를 컴파일 시 RequiredMemberAttribute 특성을 함께 추가해 컴파일합니다.

// 원본 소스 코드
public required int Age;

// 컴파일 후 
[RequiredMember]
public int Age;

저렇게 보면, 개발자가 "required" 대신 직접 [RequiredMember] 특성을 부여해도 될 것 같은데요, 하지만 실제로 해보면 ^^ C# 컴파일러가 required를 사용하라며 오류를 냅니다.

// 컴파일 오류: error CS9033: Do not use 'System.Runtime.CompilerServices.RequiredMemberAttribute'. Use the 'required' keyword on required fields and properties instead.
[RequiredMember]
public int Age;

어쨌든, required로 인해 .NET 7 BCL에는 2개의 타입(RequiredMemberAttribute, SetsRequiredMembersAttribute)이 추가되는데요, 만약 .NET 6 이하를 대상으로 하는 프로젝트에서 사용하려고 한다면 다음과 같이 직접 타입 정의를 추가하면 됩니다.

// C# 6.0 프로젝트

using System.Diagnostics.CodeAnalysis;

Employee e = new Employee("Anders");
Console.WriteLine(e);

public class Employee
{
    public required int Age;

    public string Name { get; init; }

    [SetsRequiredMembers]
    public Employee(string name)
    {
        this.Name = name;
    }
}

/* 아래의 타입을 정의하지 않으면 컴파일 오류 발생
error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RequiredMemberAttribute..ctor'
error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute..ctor'
error CS0246: The type or namespace name 'SetsRequiredMembersAttribute' could not be found (are you missing a using directive or an assembly reference?)
error CS0246: The type or namespace name 'SetsRequiredMembers' could not be found (are you missing a using directive or an assembly reference?)
*/


#if !NET7_0_OR_GREATER
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public sealed class RequiredMemberAttribute : Attribute
    {
        public RequiredMemberAttribute() { }
    }

    [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
    public sealed class CompilerFeatureRequiredAttribute : Attribute
    {
        public string FeatureName { get; }

        public CompilerFeatureRequiredAttribute(string featureName)
        {
            this.FeatureName = featureName;
        }
    }
}

namespace System.Diagnostics.CodeAnalysis
{
    [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
    public sealed class SetsRequiredMembersAttribute : Attribute
    {
        public SetsRequiredMembersAttribute() { }
    }
}
#endif





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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13222정성태1/20/20233932개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234163Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234314오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20233872Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233795VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234391디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234654디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236159Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235729.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235269오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235028기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235112웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234132Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234032Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20233963.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224270.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224475.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224871.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224152.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224311.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224705기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225330오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224204오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224492개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224368.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224308.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...