Fields vs Properties for private class variables [

2019-03-11 16:58发布

This question already has an answer here:

For private class variables, which one is preferred?

If you have a property like int limit, you want it to be:

int Limit {get; set;}

and use it inside the class, like so:

this.Limit

Is there a reason to use it or not use it? Maybe for performance reasons?

I wonder if this is a good practice.

11条回答
祖国的老花朵
2楼-- · 2019-03-11 17:05

Granted, since it's a private API, its an implementation detail - you can do whatever you want here. However, there is very little reason to not use a property, even for private classes. The properties get inlined away by the JIT, unless there is extra code in place, so there isn't really a performance impact.

The biggest reasons to prefer properties, IMO, are:

  1. Consistency in your API - You'll want properties in publicly exposed APIs, so making them in the private API will make your programming exprience more consistent, which leads to less bugs due to better maintainability
  2. Easier to convert private class to public
查看更多
姐就是有狂的资本
3楼-- · 2019-03-11 17:06

I generally follow the following principle: If it's for strictly private use, use a field as it is faster.

If you decide that it should become public, protected or internal some day, it's not difficult to refactor to a property anyway, and with tools like ReSharper, it takes about 3 seconds to do so... :)

查看更多
Bombasti
4楼-- · 2019-03-11 17:07

I would say its good practice to use a property. If ever you had to expose the limit value and used a local member it will require more coding while if its a property it would only require a change of its modifier.

I think it's cleaner also.

查看更多
smile是对你的礼貌
5楼-- · 2019-03-11 17:09

From my perspective, using properties in lieu of variables boils down to:

Pros

  • Can set a break point for debugging, as Jared mentioned,
  • Can cause side-effects, like Rex's EnsureValue(),
  • The get and set can have different access restrictions (public get, protected set),
  • Can be utilized in Property Editors,

Cons

  • Slower access, uses method calls.
  • Code bulk, harder to read (IMO).
  • More difficult to initialize, like requiring EnsureValue();

Not all of these apply to int Limit {get; set;} style properties.

查看更多
混吃等死
6楼-- · 2019-03-11 17:09

Properties provide some very good automatic features (like Json and Xml Serialization)

Fields do not.

Properties can also be a part of an Interface. If you decide to refactor later on... this might be something to consider too.

查看更多
家丑人穷心不美
7楼-- · 2019-03-11 17:10

Properties are just syntactic sugar, C# will compile them into get_PropertyName and set_PropertyName, so performance differences are not a consideration.

查看更多
登录 后发表回答