수색…


소개

nameof 연산자를 사용하면 변수 , 유형 또는 멤버 의 이름을 리터럴로 하드 코딩하지 않고 문자열 형식으로 가져올 수 있습니다.

연산은 컴파일시에 평가됩니다. 즉, IDE의 이름 바꾸기 기능을 사용하여 참조 된 식별자의 이름을 바꿀 수 있으며 이름 문자열이 함께 업데이트됩니다.

통사론

  • 이름 (표현식)

기본 사용 : 변수 이름 인쇄

nameof 연산자를 사용하면 변수, 유형 또는 멤버의 이름을 리터럴로 하드 코딩하지 않고 문자열 형식으로 가져올 수 있습니다. 이 작업은 컴파일시 평가됩니다. 즉, IDE의 이름 바꾸기 기능을 사용하여 참조 된 식별자의 이름을 바꿀 수 있으며 이름 문자열이이 식별자로 업데이트됩니다.

var myString = "String Contents";
Console.WriteLine(nameof(myString));

출력하겠습니까?

myString

변수의 이름이 "myString"이기 때문입니다. 변수 이름을 리펙토링하면 문자열이 변경됩니다.

참조 유형에서 호출 된 경우 nameof 연산자는 기본 객체의 이름이나 유형 이름이 아닌 현재 참조의 이름을 반환합니다. 예 :

string greeting = "Hello!";
Object mailMessageBody = greeting;

Console.WriteLine(nameof(greeting)); // Returns "greeting"
Console.WriteLine(nameof(mailMessageBody)); // Returns "mailMessageBody", NOT "greeting"!

매개 변수 이름 인쇄하기

단편

public void DoSomething(int paramValue)
{
    Console.WriteLine(nameof(paramValue));
}

...

int myValue = 10;
DoSomething(myValue);

콘솔 출력

paramValue

PropertyChanged 이벤트 발생

단편

public class Person : INotifyPropertyChanged
{
    private string _address;

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public string Address
    {
        get { return _address; }
        set
        {
            if (_address == value)
            {
                return;
            }

            _address = value;
            OnPropertyChanged(nameof(Address));
        }
    }
}

...

var person = new Person();
person.PropertyChanged += (s,e) => Console.WriteLine(e.PropertyName);

person.Address = "123 Fake Street";

콘솔 출력

주소

PropertyChanged 이벤트 처리

단편

public class BugReport : INotifyPropertyChanged
{
    public string Title { ... }
    public BugStatus Status { ... }
}

...

private void BugReport_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var bugReport = (BugReport)sender;

    switch (e.PropertyName)
    {
        case nameof(bugReport.Title):
            Console.WriteLine("{0} changed to {1}", e.PropertyName, bugReport.Title);
            break;

        case nameof(bugReport.Status):
            Console.WriteLine("{0} changed to {1}", e.PropertyName, bugReport.Status);
            break;
    }
}

...

var report = new BugReport();
report.PropertyChanged += BugReport_PropertyChanged;

report.Title = "Everything is on fire and broken";
report.Status = BugStatus.ShowStopper;

콘솔 출력

제목이 모두 바뀌 었습니다. 화재가 발생하여 고장났습니다.

상태가 ShowStopper로 변경되었습니다.

제네릭 형식 매개 변수에 적용됩니다.

단편

public class SomeClass<TItem>
{
    public void PrintTypeName()
    {
        Console.WriteLine(nameof(TItem));
    }
}

...

var myClass = new SomeClass<int>();
myClass.PrintTypeName();

Console.WriteLine(nameof(SomeClass<int>));

콘솔 출력

T 항목

SomeClass

정규화 된 식별자에 적용

단편

Console.WriteLine(nameof(CompanyNamespace.MyNamespace));
Console.WriteLine(nameof(MyClass));
Console.WriteLine(nameof(MyClass.MyNestedClass));
Console.WriteLine(nameof(MyNamespace.MyClass.MyNestedClass.MyStaticProperty));

콘솔 출력

MyNamespace

내 수업

MyNestedClass

MyStaticProperty

인수 검사 및 Guard 절

취하다

public class Order
{
    public OrderLine AddOrderLine(OrderLine orderLine)
    {
        if (orderLine == null) throw new ArgumentNullException(nameof(orderLine));
        ...
    }
}

위에

public class Order
{
    public OrderLine AddOrderLine(OrderLine orderLine)
    {
        if (orderLine == null) throw new ArgumentNullException("orderLine");
        ...
    }
}    

nameof 기능을 사용하면 메소드 매개 변수를 쉽게 리팩터링 할 수 있습니다.

강력한 형식의 MVC 작업 링크

일반적으로 느슨하게 입력 된 대신 :

@Html.ActionLink("Log in", "UserController", "LogIn")

강력하게 입력 된 액션 링크를 만들 수 있습니다.

@Html.ActionLink("Log in", @typeof(UserController), @nameof(UserController.LogIn))

당신이 당신의 코드를 리팩토링과 이름을 변경하려는 경우 지금 UserController.LogIn 에 방법 UserController.SignIn , 당신은 모든 문자열 발생 검색에 대해 걱정할 필요가 없습니다. 컴파일러가 작업을 수행합니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow