Programing

.NET에서 Getter 및 Setter 선언

lottogame 2020. 7. 1. 08:00
반응형

.NET에서 Getter 및 Setter 선언


이 질문에는 이미 답변이 있습니다.

게터와 세터 선언의 차이점과 선호하는 방법이 무엇인지 궁금합니다. 첫 번째는 Visual Studio에 의해 자동으로 생성 될 수 있습니다. 다른 사람은 어떻습니까? 감사

1 일

string _myProperty { get; set; }

2 위

string _myProperty;

public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

3 위

string _myProperty;

public string getMyProperty()
{
  return this._myProperty;
}

public void setMyProperty(string value)
{
  this._myProperty = value;
}

속성은 일부 데이터를 캡슐화하는 데 사용됩니다. 일반 필드를 사용할 수 있습니다.

public string MyField

그러나이 필드는 수업 외부의 모든 사용자가 액세스 할 수 있습니다. 사람들은 잘못된 값을 삽입하거나 예상치 못한 방식으로 값을 변경할 수 있습니다.

속성을 사용하면 데이터 액세스 방식을 캡슐화 할 수 있습니다. C #에는 필드를 속성으로 변환하는 좋은 구문이 있습니다.

string MyProperty { get; set; }

이를 자동 구현 속성 이라고합니다 . 필요한 경우 재산을 다음과 같이 확장 할 수 있습니다.

string _myProperty;

public string MyProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

이제 값을 확인하는 코드를 추가 할 수 있습니다 setter.

set
{
    if (string.IsNullOrWhiteSpace(value))
        throw new ArgumentNullException();

    _myProperty = value;
}

속성은 또한 getter와 setter에 대해 다른 접근자를 가질 수 있습니다.

public string MyProperty { get; private set; }

이렇게하면 모든 사람이 읽을 수 있지만 클래스 자체 만 수정할 수있는 속성을 만들 수 있습니다.

다음에 대해 완전히 사용자 정의 된 구현을 추가 할 수도 있습니다 getter.

public string MyProperty
{
    get
    {
        return DateTime.Now.Second.ToString();
    }
}

When C# compiles your auto-implemented property, it generates Intermediate Language (IL). In your IL you will see a get_MyProperty and set_MyProperty method. It also creates a backing field called <MyProperty>k_BackingField (normally this would be an illegal name in C# but in IL it's valid. This way you won't get any conflicts between generated types and your own code). However, you should use the official property syntax in C#. This creates a nicer experience in C# (for example with IntelliSense).

By convention, you shouldn't use properties for operations that take a long time.


Well, the first and second both generate something like the third in the end. However, don't use the third when you have a syntax for properties.

Finally, if you have no work to do in the get or set, then use the first.

In the end, the first and second are just some form of syntactic sugar, but why code more than what's necessary.

// more code == more bugs

And just to have a little fun, consider this:

public string A { get; private set; }

Now that's a lot more straight forward isn't it? The public modifier is implied on both the get and the set, but it can be overriden. This would of course be the same rule for any modifier used when defining the property itself.


1st

string _myProperty { get; set; }

This is called an Auto Property in the .NET world. It's just syntactic sugar for #2.

2nd

string _myProperty;

public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

This is the usual way to do it, which is required if you need to do any validation or extra code in your property. For example, in WPF if you need to fire a Property Changed Event. If you don't, just use the auto property, it's pretty much standard.

3

string _myProperty;

public string getMyProperty()
{
    return this._myProperty;
}

public string setMyProperty(string value)
{
    this._myProperty = value;
}

The this keyword here is redundant. Not needed at all. These are just Methods that get and set as opposed to properties, like the Java way of doing things.


With this, you can perform some code in the get or set scope.

private string _myProperty;
public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

You also can use automatic properties:

public string myProperty
{
    get;
    set;
}

And .Net Framework will manage for you. It was create because it is a good pratice and make it easy to do.

You also can control the visibility of these scopes, for sample:

public string myProperty
{
    get;
    private set;
}

public string myProperty2
{
    get;
    protected set;
}

public string myProperty3
{
    get; 
}

Update

Now in C# you can initialize the value of a property. For sample:

public int Property { get; set; } = 1;

If also can define it and make it readonly, without a set.

public int Property { get; } = 1;

And finally, you can define an arrow function.

public int Property { get; } => GetValue();

Just to clarify, in your 3rd example _myProperty isn't actually a property. It's a field with get and set methods (and as has already been mentioned the get and set methods should specify return types).

In C# the 3rd method should be avoided in most situations. You'd only really use it if the type you wanted to return was an array, or if the get method did a lot of work rather than just returning a value. The latter isn't really necessary but for the purpose of clarity a property's get method that does a lot of work is misleading.


Lets start with 3. That wouldnt work. public getMyProperty() has no return typ.

And number 1 and 2 are actually same things. 2 is what number 1 becomes after compilation.

So 1 and 2 are same things. with two you can have some validation or caching in your model.

other than that they become same.


The 1st one is default, when there is nothing special to return or write. 2nd and 3rd are basically the same where 3rd is a bit more expanded version of 2nd


The first one is the "short" form - you use it, when you do not want to do something fancy with your getters and setters. It is not possible to execute a method or something like that in this form.

The second and third form are almost identical, albeit the second one is compressed to one line. This form is discouraged by stylecop because it looks somewhat weird and does not conform to C' Stylguides.

I would use the third form if I expectd to use my getters / setters for something special, e.g. use a lazy construct or so.

참고URL : https://stackoverflow.com/questions/17881091/getter-and-setter-declaration-in-net

반응형