如何正确定义类属性?

发布于 2024-09-09 04:44:15 字数 927 浏览 1 评论 0原文

在项目中定义新类时,正确/最佳实践是什么? 过去我创建过如下类:

  public class MyClass
  {
      public string FirstName  {get; set;}
      public string LastName  {get; set;}
  }

通常我会使用这样的类在项目中创建集合。

然而,当我继续学习和阅读有关 c# Sharp 的更多内容时,我看到了类定义为的示例:

    class MyClass //not set to public
    {
        private string  _firstName; //first defined as fields
        private string _lastName;

        public string FirstName  // then defined as properties 
        {
            get { return  _firstName; }
            set { _firstName = value; }
        }
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
    }

第一种方法的定义是否不正确,或者这是 C# 中可接受的速记版本?作为最佳实践,您是否应该始终首先使用私有字段定义类,然后使用 get/set 值将它们定义为属性?

我问这个问题是因为我是自学 C#,我正在努力改进并更好地理解正确的开发方法,而一些示例和教程只是简单地陈述了方法,而没有明确解释为什么一种方法是首选(或应该是)完成)超过其他。

提前致谢

When defining a new class within a project what is the correct/best practice for doing so?
In the past I have created classes such as:

  public class MyClass
  {
      public string FirstName  {get; set;}
      public string LastName  {get; set;}
  }

Normally I’d use a class such as this for the creation of collections within a project.

However as I continue to learn and read more about c# sharp I see examples where classes are defined as:

    class MyClass //not set to public
    {
        private string  _firstName; //first defined as fields
        private string _lastName;

        public string FirstName  // then defined as properties 
        {
            get { return  _firstName; }
            set { _firstName = value; }
        }
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
    }

Is the first approach incorrect in definition or is this an accepted shorthand version within C#? As a best practice should you always first define the class with private fields and then define them as properties using get / set to a value?

I ask because I am self taught in C# and I am trying to improve and well as better understand the proper approach to development and some samples and tutorials out there simply state approaches without a solid explanation as to why one approach is preferred (or should be done) over the other.

Thanks in advance

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

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

发布评论

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

评论(4

你好,陌生人 2024-09-16 04:44:15

您的第一个示例:

public class MyClass
{
    public string FirstName  {get;  set;}
    public string LastName  {get;  set;}
}

具体是在 c# 中引入的 自动实现的属性 3.0。两种格式都没有错误。第一个更多的是“速记”。

对于更复杂的类型,有时使用旧样式仍然有用,并且仅公开私有变量中的某些属性或值,例如:

public class MyClass
{
    private Dictionary<int, List<string>> _someInternalDictionary;

    public int MyValuesCount
    {
        get
        {
            return _someInternalDictionary.Values.Count;
        }
    }

}

一个粗略的示例,但希望您能理解我的想法。

Your first example of:

public class MyClass
{
    public string FirstName  {get;  set;}
    public string LastName  {get;  set;}
}

is specifically Auto-Implemented Properties, introduced in c# 3.0. Neither format is wrong. The first is more of a 'shorthand'.

With more complex types, it is sometimes still useful to use the old style, and expose only certain properties or values from a private variable, such as:

public class MyClass
{
    private Dictionary<int, List<string>> _someInternalDictionary;

    public int MyValuesCount
    {
        get
        {
            return _someInternalDictionary.Values.Count;
        }
    }

}

A crude example but hopefully you get my idea.

月隐月明月朦胧 2024-09-16 04:44:15

第一个示例中的简写语法(自动实现的属性)是在 C# 3.0 中引入的,在此之前无效。编译器实际上将它们转换为带有支持字段的完整形式。

在 C# 3.0 之前,定义属性的唯一正确方法是使用支持字段。

即使使用 C# 3.0,如果您希望属性中包含任何逻辑,则需要将它们转换为使用支持字段。

简而言之 - 对于哑属性(不执行任何操作的属性),请使用自动属性。它们使您的代码更简单、更易于阅读并且可以转换。

The shorthand syntax (auto implemented properties) in your first example was introduced in C# 3.0, and was not valid before then. The compiler actually converts them to the full form with backing fields.

Before C# 3.0, the only correct way to define properties was with backing fields.

Even with C# 3.0, if you want to have any logic in your properties, you need to convert them to use backing fields.

In short - for dumb properties (those that do nothing), use auto properties. They make your code simpler and easier to read and can be converted.

盛装女皇 2024-09-16 04:44:15

实际上,您拥有的两个类在功能和特性方面是相同的。

自动属性语法(第一类)的目的基本上是为您提供一种快速的方法来声明与您显示的第二类基本相同的内容。

我会坚持使用第一个版本,直到您需要向 getter 或 setter 方法添加代码(例如验证属性的新值)。

自动属性语法的目的是双重的,添加它部分是为了方便 Linq,部分是为了方便 Linq。添加是为了更轻松地确保您声明属性,而不是公共字段。

如果您使用自动属性声明一个类(同样是第一个版本),那么针对您的代码编译的所有其他程序集都会知道您的类将这些内容声明为属性,而不是字段。如果您后来决定需要添加代码(例如验证),则不必重新编译那些其他程序集,因为它们仍然可以找到属性。

The two classes you have are in practice identical in functionality and features.

The purpose of the automatic properties syntax (the first class) is to basically give you a quick way to declare what is essentially the same as the second class you show.

I would stick with the first version until you need to add code to the getter or setter method (like validating a new value for the property.)

The purpose of the automatic property syntax is dual, it was partly added to facilitate Linq, and partly added to make it easier to just ensure you declare properties, and not public fields.

If you declare a class using automatic properties (again, the first version), then all other assemblies compiled against your code will know that your class declares these things as properties, and not as fields. If you later decide that you need to add code, like validation, those other assemblies does not have to be recompiled, since they still find the properties.

憧憬巴黎街头的黎明 2024-09-16 04:44:15

您还可以使用访问修饰符进行获取和设置...

public {ReturnType} MyProperty { {Access Modifier}get; {Access Modifier}set; }

我假设您已经了解访问修饰符

You could also use Access Modifier for get and set...

public {ReturnType} MyProperty { {Access Modifier}get; {Access Modifier}set; }

And I assume that you already have knowledge of Access Modifier.

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