C# 自动属性

发布于 2024-08-03 01:23:10 字数 258 浏览 3 评论 0原文

我对 C# 中的自动属性点有点困惑,例如,

public string Forename{ get; set; }

我知道您通过不必声明私有变量来保存代码,但是当您不使用任何获取或设置逻辑时,属性的意义何在?为什么不直接使用

public string Forename; 

我不确定这两个语句之间的区别是什么,我一直认为如果您想要额外的获取/设置逻辑,您使用属性?

I'm a bit confused on the point of Automatic properties in C# e.g

public string Forename{ get; set; }

I get that you are saving code by not having to declare a private variable, but what's the point of a property when you are not using any get or set logic? Why not just use

public string Forename; 

I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

南风起 2024-08-10 01:23:10

属性可以在不破坏契约的情况下将代码放入其中,字段不能在不将其更改为属性(并破坏接口)的情况下将代码放入其中。属性可以只读或只写,而字段则不能。属性可以进行数据绑定,而字段则不能。

Properties can have code put into them without breaking contract, fields can't have code put into them without changing them to properties (and breaking the interface). Properties can be read only or write only, fields can't. Properties can be data bound, fields can't.

雪化雨蝶 2024-08-10 01:23:10

您可以写入

public string Forename{ get; private set; }

以获取只读属性...仍然不如真实属性那么通用,但对于某些作品来说这是一种折衷。

You can write

public string Forename{ get; private set; }

to get read-only properties... Still not nearly as versatile as real properties, but it's a compromise that for some works.

只为守护你 2024-08-10 01:23:10

我不确定这两个语句之间有什么区别,我一直认为如果您想要额外的获取/设置逻辑,您会使用属性?

在第一种情况下,编译器会自动为您添加一个字段,并包装该属性。这基本上等同于:

private string forename;
public string Forename
{
    get
    { 
        return this.forename;
    }
    set
    {
        this.forename = value;
    }
}

使用属性比字段有很多优点。即使您不需要某些特定原因(例如数据绑定),这也有助于您的 API 面向未来。

主要问题是,如果您创建了一个字段,但在应用程序的 v2 中需要一个属性,则会破坏 API。通过预先使用自动属性,您可以随时更改 API,而无需担心源代码或二进制兼容性问题。

I'm not sure what the difference between these 2 statements is, I always thought you used properties if you wanted additional get/set logic?

In the first case, the compiler will automatically add a field for you, and wrap the property. It's basically the equivalent to doing:

private string forename;
public string Forename
{
    get
    { 
        return this.forename;
    }
    set
    {
        this.forename = value;
    }
}

There are many advantages to using properties over fields. Even if you don't need some of the specific reasons, such as databinding, this helps to future-proof your API.

The main problem is that, if you make a field, but in v2 of your application, need a property, you'll break the API. By using an automatic property up front, you have the potential to change your API at any time, with no worry about source or binary compatibility issues.

晨光如昨 2024-08-10 01:23:10

这意味着您希望稍后添加逻辑。

如果您这样做并从一开始就将其作为属性,则无需重建依赖代码。如果您将其从变量更改为属性,那么您将不得不这样做。

It is meant that you expect to add the logic later.

If you do so and have it as property from the beginning, you will not have to rebuild the dependent code. If you change it from a variable to a property, then you will have to.

向地狱狂奔 2024-08-10 01:23:10

公共数据成员是邪恶的(因为对象不控制对其自身状态的修改 - 它成为全局变量)。打破封装——OOP 的一个原则。

自动属性可以提供封装并避免为简单属性编写样板代码的苦差事。

public string ID { get; set;}

您将来可以将自动属性更改为非自动属性(例如,您在设置器中进行一些验证)...并且不会破坏现有客户端。

string m_ID;
public string ID
{
   get { return m_ID; }
   set 
   { 
     //validate value conforms to a certain pattern via a regex match
     m_ID = value;
   }
}

您不能对公共数据属性执行相同的操作。将数据属性更改为属性将强制现有客户端重新编译,然后才能再次交互。

Public data members are evil (in that the object doesn't control modification of it's own state - It becomes a global variable). Breaks encapsulation - a tenet of OOP.

Automatic properties are there to provide encapsulation and avoid drudgery of writing boiler plate code for simple properties.

public string ID { get; set;}

You can change automatic properties to non-automatic properties in the future (e.g. you have some validation in a setter for example)... and not break existing clients.

string m_ID;
public string ID
{
   get { return m_ID; }
   set 
   { 
     //validate value conforms to a certain pattern via a regex match
     m_ID = value;
   }
}

You cannot do the same with public data attributes. Changing a data attribute to a property will force existing clients to recompile before they can interact again.

高速公鹿 2024-08-10 01:23:10

添加自动属性时,编译器会将获取设置逻辑添加到应用程序中,这意味着如果您稍后添加此逻辑,则从外部库对属性的引用仍然有效。

如果您从公共变量迁移到属性,这对于引用您的库的其他库来说将是一个重大更改 - 因此,为什么不从自动属性开始呢? :)

When adding auto properties the compiler will add get set logic into the application, this means that if you later add to this logic, and references to your property from external libraries will still work.

If you migrated from a public variable to a property, this would be a breaking change for other libraries that reference yours - hence, why not start with an auto property? :)

老旧海报 2024-08-10 01:23:10

其一,您可以将属性设置为 virtual 并在继承类中实现逻辑。
之后您还可以在同一个类中实现逻辑,并且不会对依赖该类的任何代码产生副作用。

For one, you can set the property to virtual and implement logic in an inheriting class.
You can also implement logic in the same class afterwards and there won't be side-effects on any code relying on the class.

自演自醉 2024-08-10 01:23:10

并非所有属性都需要获取/设置逻辑。如果是这样,您可以使用私有变量。
例如,在 MV-something 模式中,您的模型不会有太多逻辑。但您可以根据需要混合搭配。

如果您要使用您建议的字段来代替属性,则您无法定义一个接口来正确描述您的类,因为接口不能包含数据字段。

Not all properties need get/set logic. If they do, you use a private variable.
For example, in a MV-something pattern, your model would not have much logic. But you can mix and match as needed.

If you were to use a field like you suggested in place of a property, you can't for example define an interface to describe your class correctly, since interfaces cannot contain data fields.

终遇你 2024-08-10 01:23:10

属性就像合同,您可以更改属性的实现,而不会影响使用您的类和属性的客户端。今天您可能没有任何逻辑,但随着业务需求的变化,如果您想引入任何代码,属性是您最安全的选择。以下 2 个链接是优秀的 C# 视频教程。第一个视频解释了对属性的需求而不是仅使用字段,第二个视频解释了不同类型的属性。我发现它们非常有用。

C# 中属性的需要< /a>

属性C#,只读,只写,读/写,自动实现

A property is like a contract, and you can change the implemenation of a property without affecting the clients using your classes and properties. You may not have any logic today, but as business requirements change and if you want to introduce any code, properties are your safest bet. The following 2 links are excellent c# video tutorials. The first one explains the need of properties over just using fields and the second video explains different types of properties. I found them very useful.

Need for the Properties in C#

Poperties in C#, Read Only, Write Only, Read/Write, Auto Implemented

你是年少的欢喜 2024-08-10 01:23:10

看看下面的代码和解释。
属性最常见的实现是 getter 或 setter,它们只是读取和写入与属性相同类型的私有字段。自动属性声明指示编译器提供此实现。编译器自动生成私有支持字段。
查看以下代码:-

    public class Stock 
    {
      decimal currentPrice ;  // private backing field.
      public decimal CurrentPrice 
      {
        get { return currentPrice ; }
        set { currentPrice = value ; }
      }
   }

相同的代码可以重写为:-

   public class Stock
   {
     public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
   }

源:- C# in a Nutshell

Take a look at the following code and explanation.
The most common implementation for a property is getter or a setter that simply reads and writes to a private field of the same type as a property. An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates a private backing field.
Look into the following code:-

    public class Stock 
    {
      decimal currentPrice ;  // private backing field.
      public decimal CurrentPrice 
      {
        get { return currentPrice ; }
        set { currentPrice = value ; }
      }
   }

The same code can be rewritten as :-

   public class Stock
   {
     public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
   }

SOURCE:- C# in a Nutshell

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文