programing

C #의 자동 속성이란 무엇이며 그 용도는 무엇입니까?

nasanasas 2021. 1. 6. 08:25
반응형

C #의 자동 속성이란 무엇이며 그 용도는 무엇입니까?


누군가가 C #의 자동 속성, 용도 및 몇 가지 예에 대한 매우 간단한 설명을 제공 할 수 있습니까? 평신도의 관점에서 일을 유지하십시오, 제발!


자동 속성은 속성 접근 자에 추가 논리가 필요하지 않을 때 사용됩니다.
선언은 다음과 같습니다.

public int SomeProperty { get; set; }

그들은 단지 구문상의 설탕이므로 다음과 같은 더 긴 코드를 작성할 필요가 없습니다.

 private int _someField;
 public int SomeProperty 
 {
    get { return _someField;}
    set { _someField = value;}
 }

편집 : 약간 확장하면 클래스에서 개인 변수를 쉽게 가질 수 있지만 클래스 외부에서 볼 수 있도록 허용합니다 (수정할 수 없음).

아, 그리고 자동 속성의 또 다른 장점 은 인터페이스에서 사용할 수 있다는 것입니다 ! (어떤 종류의 멤버 변수도 허용하지 않음)

일반 속성을 사용하면 다음과 같이 할 수 있습니다.

private string example;
public string Example 
{
    get { return example; }
    set { example = value; }
}

자동 속성을 사용하면 정말 간결한 것을 만들 수 있습니다.

public string Example { get; set; }

따라서 클래스 내에서만 설정할 수있는 필드를 만들려면 다음을 수행 할 수 있습니다.

public string Example { get; private set; }

이것은 다음과 같습니다.

private string example;
public string Example 
{
    get { return example; }
    private set { example = value; }
}

또는 Java :

private String example;

public String getExample() {
    return example;
}

public void setExample(String value) {
    example = value;
}

편집 : @Paya는 또한 나에게 경고했습니다.


속성 또는 자동 속성을 사용하는 이유를 묻는다면 이것이 바로 디자인 철학입니다.

한 가지 중요한 디자인 원칙은 필드를 공개로 노출 하지 않고 항상 속성을 통해 모든 것에 액세스한다는 것입니다. 이는 필드에 액세스 할 때를 알 수없고 더 중요한 것은 언제 설정되었는지 알 수 없기 때문입니다. 이제 대부분의 경우 값을 설정하거나 가져 오는 동안 처리가 필요하지 않습니다 (예 : 범위 확인). 이것이 자동 속성이 만들어진 이유입니다. 속성을 만드는 간단한 한 줄 방법입니다. 이에 대한 백업 저장소는 컴파일러에 의해 생성됩니다.

이것이 제가 내부 프로그램을 위해서도하는 일이지만, 아마도 공공 용도 (판매용, 오픈 소스 등)를 위해 설계된 프로그램에서 더 중요 할 것입니다. 자동 속성을 사용하고 나중에 set또는 에서 다른 작업을 수행해야한다고 결정 get하면 공용 인터페이스를 중단하지 않고 코드를 쉽게 변경할 수 있습니다.

최신 정보

아래 주석에 대한 설명으로 모든 코드가 자신의 것이라면 아니요, 속성과 필드 사이에 큰 차이를 만들지 못할 수 있습니다. 그러나 다른 사용자가 사용할 라이브러리를 디자인하는 경우 라이브러리를 사용하는 코드를 먼저 다시 컴파일하지 않는 한 공용 필드와 속성을 앞뒤로 전환하면 예외가 발생합니다.

테스트로 라이브러리 프로젝트를 만들고 TestData. 이 라이브러리를 사용하기 위해 완전히 새로운 프로젝트를 만들었습니다. 모두 예상대로 작동했습니다. 그런 다음 속성을 공용 필드 (이름은 동일하게 유지됨)로 변경하고 소비 프로젝트를 다시 컴파일하지 않고 새 라이브러리 DLL 위에 복사했습니다. 결과는 코드가 메서드 get_TestData메서드 속성을 찾을 것으로 예상했기 때문에 예외가 throw set_TestData되었지만 메서드를 통해 필드에 액세스 할 수 없습니다.

Unhandled Exception: System.MissingMethodException: Method not found: 'Void TestLibrary.TesterClass.set_TestData(System.String)'.
   at TestLibraryConsumer.Program.Main(String[] args)

이것은 프로그래머에게 몇 번의 키 입력을 저장하는 코딩 단축키 일뿐입니다. 이 모든 것을 입력하는 대신 :

private string _lastName;
public string LastName {
    get {
        return _lastName;
    }
    set {
        _lastName = value;
    }
}  

다음을 입력하면됩니다.

public string LastName {
    get; set;
} 

컴파일러가 나머지를 자동으로 생성하도록합니다.


에서 속성 (C # 프로그래밍 가이드) 자동 구현 :

C # 3.0 이상에서 자동 구현 속성은 속성 접근 자에 추가 논리가 필요하지 않을 때 속성 선언을 더 간결하게 만듭니다. 또한 클라이언트 코드에서 개체를 만들 수 있습니다.
속성을 선언하면 컴파일러는 속성의 get 및 set 접근자를 통해서만 액세스 할 수있는 익명의 비공개 지원 필드를 만듭니다.

class Person
{
       public string Name { get; set; }
}

I מ 이전 버전의 C #에서 속성을 사용하려면 값을 저장할 필드 (Backing Store라고 함)를 만들어야합니다.

private string _something;
public string Prop { get { return _something; } }

C # 3.0부터는이 요구 사항이 더 이상 필요하지 않으며 컴파일러가 자동으로 백업 저장소를 생성하므로 _something 필드를 선언 할 필요가 없습니다.

이 문제에 대한 자세한 내용은 http://msdn.microsoft.com/en-us/library/bb384054.aspx 에서 확인할 수 있습니다 .

도움이 되었기를 바랍니다.


허용되는 답변을 단순화 하면 다음을 사용할 수도 있습니다 .

public int SomeProperty { get; private set; }

동일한 효과가 있으며 더 이상이를 위해 다른 변수를 만들 필요가 없습니다.


많은 사람들이 이미 자동 속성이 문법적 설탕이라고 말했는데, 이는 간단한 속성을 쓰는 간단한 방법입니다. 공용 변수와 공용 속성의 차이점과 둘 사이를 전환 할 때 다시 컴파일해야하는 이유를 다룰 것입니다. 다음을 수행하십시오.

public class MyClass
{
    public int MyPublicVariable = 0;

    public int MyPublicProperty
    {
        get;
        set;
    }
}

개념적으로 컴파일되면 실제로 다음과 유사하게됩니다.

public class MyClass
{
    public int MyPublicVariable = 0;

    private int MyPublicProperty = 0;

    public int get_MyPublicProperty()
    {
        return MyPublicProperty;
    }

    public void set_MyPublicProperty( int value )
    {
        MyPublicProperty = value;
    }
}

오래 전에 속성은 get 및 set 메서드 쌍을 정의하는 빠르고 쉬운 방법으로 발명되었습니다. 의도를 전달하고 일관성을 보장하므로 코드를 더 읽기 쉽고 이해하기 쉽게 만들었습니다.

MyClass myClass = new MyClass();

myClass.MyPublicVariable = 2;

myClass.MyPublicProperty = 2;

Once compiled, again conceptually, it ends up being similar to the following:

MyClass myClass = new MyClass();

myClass.MyPublicVariable = 2;

myClass.set_MyPublicProperty( 2 );

So, one of the reasons for preferring public properties over public variables is if you need to use different logic as your code evolves then consumers of your code don't necessarily need to re-compile. This is why it is often considered best practice. It is also the reason auto properties were invented - to speed along code writing whilst maintaining this best practice.

There has also been some comments about interfaces. Interfaces are essentially a contract that guarantees the presence of certain methods within any class implementing them. As we know from the above, properties represent one or two methods so they work just fine in interfaces.

Hope this helps a little.

Here is another example that may be of interest:

public class MyClass
{
    private int[] _myArray = new int[ 5 ];

    public int MyArray[ int index ]
    {
        get
        {
            return _myArray[ index ];
        }
        set
        {
            _myArray[ index ] = value;
        }
     }
}
public class MyClass
{
    private int[] _myArray = new int[ 5 ];

    public int get_MyArray( int index )
    {
        return _myArray[ index ];
    }

    public void set_MyArray( int index, int value )
    {
        _myArray[ index ] = value;
    }
}

Please note: I cannot exactly remember the method signatures used when decompiling properties. I think it is 'get_XXX' and 'set_XXX' but it could be something else that is very similar. As long as the understanding is there, it probably doesn't matter too much. In the end, they all become memory addresses anyway :-)


For any VB.NET readers, this is implemented slightly differently. Eg:

''' <summary>The property is declared and can be initialized.</summary>
Public Property MyProperty As String = "SomeValue"

However, the associated field is explicitly available by prefixing an underscore:

Dim sConcat As String = _MyProperty + _MyProperty
_MyProperty = sConcat

And in external code:

Dim sMyValue As String = oMyClassObj.MyProperty ' = "SomeValueSomeValue"

Personally, I like this approach better as you can clearly see in your consuming code when you're working with internal fields or possibly-exposed properties.


Use below code:

using System;

class My Class
{
    public string Dummy { get; set; }

    public My Class()
    {
        Dummy = "I'm dummy property";
    }
}

class Program 
{
    static void Main() 
    {
            var my Class = new My Class();
             Console .Write Line (my Class .Dummy);
    }
}

ReferenceURL : https://stackoverflow.com/questions/6001917/what-are-automatic-properties-in-c-sharp-and-what-is-their-purpose

반응형