Programing

게터, 세터 및 속성 모범 사례.

crosscheck 2020. 9. 10. 07:13
반응형

게터, 세터 및 속성 모범 사례. 자바 대 C #


나는 지금 C # 수업을 듣고 있으며 최선의 방법을 찾으려고 노력하고 있습니다. 저는 Java 배경에서 왔으므로 Java 모범 사례에만 익숙합니다. 저는 C # 초보자입니다!

Java에서 개인 속성이 있으면 이렇게합니다.

private String name;

public void setName(String name) {
   this.name = name;
}

public String getName() {
   return this.name;
}

C #에서는 여러 가지 방법이 있음을 알 수 있습니다.

Java처럼 할 수 있습니다.

private string name;

public void setName(string name) {
   this.name = name;
}

public string getName() {
   return this.name;
}

또는 이렇게 할 수 있습니다.

private string name;

public string Name {
   get { return name; }
   set { name = value; }
}

또는:

public string Name { get; set; }

어떤 것을 사용해야하며 각 접근 방식과 관련된주의 사항이나 미묘한 점은 무엇입니까? 클래스를 만들 때 Java에서 알고있는 일반적인 모범 사례를 따르고 있습니다 (특히 효과적인 Java 읽기). 예를 들어, 저는 불변성을 선호합니다 (필요한 경우에만 setter 제공). 저는 이러한 관행이 C #에서 setter와 getter를 제공하는 다양한 방법에 어떻게 부합하는지 궁금합니다. 본질적으로 Java 세계의 모범 사례를 C #으로 어떻게 변환합니까?

편집하다

나는 이것을 Jon Skeet의 답변에 대한 의견으로 게시했지만 오래되었습니다.

사소하지 않은 속성 (즉, 상당한 처리 및 유효성 검사 포함)은 어떻습니까? 나는 아직도 공용 속성을 통해 만에 캡슐화 된 논리에 노출 수 getset? 전용 setter 및 getter 메서드 (관련 처리 및 유효성 검사 논리 포함)를 사용하여이 작업을 수행해야하는 이유는 무엇입니까?


C # 6 이전

나는 사소한 속성을 위해 이들 중 마지막을 사용합니다. getter와 setter가 모두 공용 이므로 이것을 공용 속성이라고합니다.

불변성은 자동으로 구현 된 속성으로 인해 약간의 고통입니다. getter 만있는 자동 속성을 작성할 수 없습니다. 가장 가까운 곳은 다음과 같습니다.

public string Foo { get; private set; }

이것은 정말로 불변 하지 않습니다 . 클래스 밖에서는 불변입니다. 따라서 실제 읽기 전용 속성을 대신 사용할 수 있습니다 .

private readonly string foo;
public string Foo { get { return foo; } }

당신은 확실히 쓰고 싶지 않아 getName()setName(). 에서 일부 의 경우 그것은 그들이 비싼 수있는 경우 특히, 쓰기 가져 오기 / 설정 방법보다는 사용하여 속성에 의미가 있습니다 그리고 당신은 그것을 강조하고 싶습니다. 그러나 메서드에 대한 PascalCase의 .NET 명명 규칙을 따르고 싶을 것이고 어쨌든 일반적인 메서드로 이와 같은 사소한 속성을 구현하는 것을 원하지 않을 것입니다. 여기서 속성은 훨씬 더 관용적입니다.

C # 6

만세, 마침내 적절한 읽기 전용 자동 구현 속성이 있습니다.

// This can only be assigned to within the constructor
public string Foo { get; }

Likewise for read-only properties which do need to do some work, you can use member-bodied properties:

public double Area => height * width;

If all you need is a variable to store some data:

public string Name { get; set; }

Want to make it appear read-only?

public string Name { get; private set; }

Or even better...

private readonly string _name;

...

public string Name { get { return _name; } }

Want to do some value checking before assigning the property?

public string Name 
{
   get { return m_name; }
   set
   {
      if (value == null)
         throw new ArgumentNullException("value");

      m_name = value;
   }
}

In general, the GetXyz() and SetXyz() are only used in certain cases, and you just have to use your gut on when it feels right. In general, I would say that I expect most get/set properties to not contain a lot of logic and have very few, if any, unexpected side effects. If reading a property value requires invoking a service or getting input from a user in order to build the object that I'm requesting, then I would wrap it into a method, and call it something like BuildXyz(), rather than GetXyz().


Use properties in C#, not get/set methods. They are there for your convenience and it is idiomatic.

As for your two C# examples, one is simply syntactic sugar for the other. Use the auto property if all you need is a simple wrapper around an instance variable, use the full version when you need to add logic in the getter and/or setter.


In C# favor properties for exposing private fields for get and/or set. The thie form you mention is an autoproperty where the get and set automatically generate a hidden pivot backing field for you.

I favor auto properties when possible but you should never do a set/get method pair in C#.


public string Name { get; set; }

This is simply a auto-implemented property, and is technically the same as a normal property. A backing field will be created when compiling.

All properties are eventually converted to functions, so the actual compiled implementation in the end is the same as you are used to in Java.

Use auto-implemented properties when you don't have to do specific operations on the backing field. Use a ordinary property otherwise. Use get and set functions when the operation has side effects or is computationally expensive, use properties otherwise.


First let me try to explain what you wrote:

// private member -- not a property
private string name;

/// public method -- not a property
public void setName(string name) {
   this.name = name;
}

/// public method -- not a property
public string getName() {
   return this.name;
}

// yes it is property structure before .Net 3.0
private string name;
public string Name {
   get { return name; }
   set { name = value; }
}

This structure is also used nowadays but it is most suitable if you want to do some extra functionality, for instance when a value is set you can it to parse to capitalize it and save it in private member for alter internal use.

With .net framework 3.0

// this style is introduced, which is more common, and suppose to be best
public string Name { get; set; }

//You can more customize it
public string Name
{
    get;
    private set;    // means value could be set internally, and accessed through out
}

Wish you better luck in C#


Regardless of which way you choose in C# the end result is the same. You will get a backinng variable with separate getter and setter methods. By using properties you are following best practices and so it's a matter of how verbose you want to get.

Personally I would choose auto-properties, the last version: public string Name { get; set; }, since they take up the least amount of space. And you can always expand these in the future if you need add something like validation.


Whenever possible I prefer public string Name { get; set; } as it's terse and easily readable. However, there may be times when this one is necessary

private string name;

public string Name {
   get { return name; }
   set { name = value; }
}

In C# the preferred way is through properties rather than getX() and setX() methods. Also, note that C# does not require that properties have both a get and a set - you can have get-only properties and set-only properties.

public boolean MyProperty
{
    get { return something; }
}

public boolean MyProperty
{
    set { this.something = value; }
}

As mentioned, all of these approaches result in the same outcome. The most important thing is that you pick a convention and stick with it. I prefer using the last two property examples.


like most of the answers here, use Automatic properties. Intuitive, less lines of code and it is more clean. If you should serialize your class, mark the class [Serializable]/ with [DataConract] attribute. And if you are using [DataContract] mark the member with

[DataMember(Name="aMoreFriendlyName")]
public string Name { get; set; }

Private or public setter depends on your preference.

Also note that automatic properties require both getters and setters(public or private).

/*this is invalid*/
public string Name 
{ 
    get; 
   /* setter omitted to prove the point*/
}

Alternatively, if you only want get/set, create a backing field yourself


Which one should I use, and what are the caveats or subtleties involved with each approach?

When going with properties there is one caveat that has not been mentioned yet: With properties you cannot have any parametrization of your getters or setters.

For example imagine you want to retrieve a list items and want to also apply a filter at the same time. With a get-method you could write something like:

obj.getItems(filter);

In contrast, with a property you are forced to first return all items

obj.items

and then apply the filter in the next step or you have to add dedicated properties that expose items filtered by different criteria, which soon bloats your API:

obj.itemsFilteredByX
obj.itemsFilteredByY

What sometimes can be a nuisance is when you started with a property, e.g. obj.items and then later discovered that getter- or setter-parametrization is needed or would make things easier for the class-API user. You would now need to either rewrite your API and modify all those places in your code that access this property or find an alternative solution. In contrast, with a get-method, e.g. obj.getItems(), you can simply extend your method's signature to accept an optional "configuration" object e.g. obj.getItems(options) without having to rewrite all those places that call your method.

That being said, (auto-implemented) properties in C# are still very useful shortcuts (for the various reasons mentioned here) since most of the time parametrization may not be needed – but this caveat stands.

참고URL : https://stackoverflow.com/questions/4948816/getters-setters-and-properties-best-practices-java-vs-c-sharp

반응형