Programing

속성과 변수의 차이점은 무엇입니까

lottogame 2020. 11. 12. 07:39
반응형

속성과 변수의 차이점은 무엇입니까


속성과 변수를 이해하는 데 혼란이 있습니다.

public class ABC()
{
    public int A;
    public int B { get; set; }
}

A와 B의 정확한 차이점은 무엇입니까?


많은 사람들이 지적했듯이 A는 필드 이고 B는 속성 입니다.

진짜 질문은, 왜 관심을 가져야하고 무엇을 사용해야합니까?

Jonathan Aneja블로그 게시물을 참조합니다 .

(VB에 있지만 C #에도 적용됩니다.))

필드에 속성을 사용하는 이유는 다음과 같습니다.

1. 인터페이스에서 필드를 사용할 수 없습니다.

인터페이스를 통해 개체의 공개 계약에서 필드의 존재를 강제 할 수 없습니다. 속성의 경우 잘 작동합니다.

2. 검증

현재 애플리케이션에서 특정 값을 설정하는 데 유효성 검사 논리가 필요하지 않을 수 있지만 비즈니스 요구 사항을 변경하려면 나중에이 논리를 삽입해야 할 수 있습니다. 이 시점에서 필드를 속성으로 변경하는 것은 API 소비자에게 큰 변화입니다. (예를 들어 누군가가 리플렉션을 통해 클래스를 검사하는 경우).

3. 이진 직렬화

이진 직렬화를 사용하는 경우 필드를 속성으로 변경하는 것은 주요 변경 사항입니다. 덧붙여서, 이것이 VB10의 자동 구현 속성에 "바인딩 가능한"지원 필드가있는 이유 중 하나입니다 (즉, 코드에서 지원 필드의 이름을 표현할 수 있음). 자동 구현 속성을 확장 속성으로 변경하는 경우 , 지원 필드 이름을 동일하게 유지하여 직렬화 호환성을 유지할 수 있습니다 (C #에서는 바인딩 할 수없는 이름으로 지원 필드를 생성하기 때문에 변경해야합니다).

4. 많은 .NET 데이터 바인딩 인프라가 필드가 아닌 속성에 바인딩됩니다.

나는 그것이 좋은 일인지 아닌지에 대해 양측의 주장을 들었지만 현실은 그것이 현재 작동하는 방식입니다. (내 메모 : WPF 바인딩은 속성에서 작동합니다)

5. 공개 필드를 노출하는 것은 FxCop 위반입니다.

위에 나열된 많은 이유 때문에 :)

더 많은 이유가있을 수 있습니다.

또한 Jeff Atwood블로그 게시물 을 가리키고 그 내용을 인용하여 마무리하고 싶습니다 .

여기서 정말 중요한 것은 중요하지 않은 코드 작성을 피하는 것입니다. 그리고 공용 변수를 둘러싼 속성 래퍼는 무의미한 코드의 핵심입니다.


A는 필드이고 B는 속성입니다. 속성은 기본적으로 getter 및 setter의 구문 설탕입니다. 정의한 클래스는 다음과 같이 컴파일됩니다.

public class ABC()
{
    public int A;

    private int backing_B;

    public void set_B(int value)
    {
        backing_B = value;
    }

    public int get_B()
    {
        return backing_B;
    }
}

이러한 종류의 변환은 모든 C # 속성에 적용됩니다. ABC.B에 대한 액세스는 메서드 호출로 변환됩니다. 속성은 기본적으로 "변수"의 환상을 제공하는 동시에 실제로는 영리하게 위장한 메서드 쌍입니다.

이것은 값의 유효성을 검사하거나 다른 흥미로운 작업을 수행 할 수있는 자체 get 및 set 메서드 본문 을 선언 할 수 있기 때문에 중요합니다 .

private int b;

public int B {
    get { return b; }
    set {
        if (value < 0) throw new ArgumentOutOfRangeException("value");
        b = value;
    }
}

대부분의 속성은 필드를 사용하여 값을 저장합니다. 속성은 필드를 제외하고 자체적으로 거의 존재하지 않습니다.


속성은 일종의 짧은 getter 및 / 또는 setter입니다. 당신은에 로직을 추가 할 수 있습니다 set또는 get재산의 또는이 (가 공공 인 경우) 변수가 항상 액세스 할 수있는 아웃 측면에서 접근하지 못하도록하는 수단들을 비공개로.


C #에서는 getter 및 setter가있는 "변수"를 속성이라고합니다. 변수에는 getter와 setter가 없거나 그래서 교과서에서 말하는 것입니다.

내 프로그래밍 강사는 우리가 Java로 만든 거의 모든 변수에 대한 getter와 setter를 만들었습니다. 인덱싱 변수조차도 글로벌 클래스 범위에서 선언 된 경우 getter 및 setter를 사용하도록했습니다. 나는 이것이 지나친 일이라고 생각하지만 게터와 세터를 만들게했습니다.

게터와 세터에 대한 진정한 점은 내부 변수를 설정하는 것보다 더 많은 일을 할 가능성이 높다는 것입니다. 대부분의 setter는 데이터가 변수로 설정 될 수 있는지 확인하기 위해 일부 유형의 데이터 유효성 검사를 수행합니다. getter는 일부 기준에 대한 반환 데이터를 확인할 수도 있습니다.

If your property is private and your setters and getters are public technically anyone could access your variable and change it as if they had public access to the actual variable. So, in reality, you should check your data to make certain that it is valid or some other data check.

private int myVariable;
public int myVariable 
{
    get 
    { 
       return myVariable; 
    }
    set 
    {
        if (value < 0) 
        { 
           throw new Exception("This is your exception some where else in code");
        }
        myVariable = value; //remember value is something that is
                            //declared automatically
    }
}

public string FirstName { get; set; }

The above is a shorthand way of writing the following

private string firstName;

public string FirstName
{
    get
    {
       //...code here
    }

    set
    {
       //...code here
    }
}

Variable is, well, a variable.

Property is a special type of method that exposes that variable. And since it is a method, therefore, you can do some other things in it apart from just exposing the variable.

From MSDN:

The Property statement introduces the declaration of a property. A property can have a Get procedure (read only), a Set procedure (write only), or both (read-write). You can omit the Get and Set procedure when using an auto-implemented property. For more information, see Auto-Implemented Properties (Visual Basic).

You can use Property only at class level. This means the declaration context for a property must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.

By default, properties use public access. You can adjust a property's access level with an access modifier on the Property statement, and you can optionally adjust one of its property procedures to a more restrictive access level.


In your example A is a public field on the class ABC and B is a public property on the class ABC. Specifically, B is an auto-implemented property. What this means is that "under the hood" the compiler does some of the work for you and effectively transforms your code into:

public class ABC()
{
   private int b;

   public int A;
   public int B
   {
       get
       {
          return b;
       }
       set
       {
          b = value;
       }
   }
}

Variable is defined basically for accessing value from a class or into the same class according to their modifier assigned to those variable.

When we define a property there two methods created for single property so extra overhead is generated that is the drawback of property.

The advantages of properties is to get or set value into private variable of class.


There is a very good article (link below) about using fields/variables vs Properties from Microsoft itself. Though the article essentially talks about a FxCop violation rule, it clearly defines the difference between the two and the exact usage guidelines.

An excerpt from the article:

The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. Accessing a property is as easy as accessing a field, and the code in a property's accessors can change as the type's features expand without introducing breaking changes.

Refer: https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-3.0/ms182141(v=vs.80)

참고URL : https://stackoverflow.com/questions/4142867/what-is-the-difference-between-a-property-and-a-variable

반응형