跳过模型类上的字段

发布于 2024-08-09 23:40:33 字数 311 浏览 4 评论 0原文

最近,在阅读了互联网上的大量教程后,我注意到一些开发人员跳过在模型类中编写字段,而只是使用属性,如下所示:

public class MyClass
{
    public string MyProperty { get; private set; }
}

除了编写更少的代码之外,这样做到底有什么好处那是?虽然我确实意识到设置器是私有的,但是当您不指定私有字段时,是否会出现某种安全问题?换句话说:这里的最佳实践是什么?编写没有字段和相关属性的模型类,或者只使用这些公共属性而不使用字段?

预先感谢,

Recently, after reading a lot of tutorials around the Internet, I've noticed that some developers skips writing the fields in their model classes and just go with properties, like this:

public class MyClass
{
    public string MyProperty { get; private set; }
}

What exactly is the benefit of doing this, apart from writing less code that is? While I do realize that the setter is private, isn't there some kind of security issues when you don't specify your private fields? In other words: what's the best practice here? Writing model classes without fields and related properties, or just go with these public properties without the fields?

Thanks in advance,

Bo

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

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

发布评论

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

评论(2

苯莒 2024-08-16 23:40:33

在c# 3.0及以上版本中,编译器会帮你将局部变量放入MSIL中。它使代码更易于阅读且更易于维护(需要跟踪的变量更少等)。

不应该有安全问题,因为它在内部创建本地范围的成员变量。

有关详细信息,请参阅 Microsoft 文档

In c# 3.0 and above, the compiler will put the local variables into the MSIL for you. It makes the code easier to read and more maintainable (less variables to keep track of, etc).

There should be no security issue because internally it is creating locally scoped member variables.

See Microsoft's documentation for more info.

飘然心甜 2024-08-16 23:40:33

如果您没有对变量进行任何操作,只是按原样设置并读取它们,那么为什么要添加额外的代码来创建私有变量并执行完整的 setter 和 getter?

C# 将创建私有变量,因此字节码仍然正确,但对于任何阅读您的程序的人来说,更容易理解发生了什么。

任何时候只要你能让代码更容易阅读,即使编译器中有语法糖,这也是一种胜利。

但是,如果您必须执行任何操作,例如检查属性是否在某个范围内,那么,在 C#3 中您仍然需要自己编写其他所有内容。

最好的做法是按照问题中的内容来写。

If you are not doing any operations on the variables, just setting them and reading them, as they are, then why add the extra code to create a private variable and do the complete setter and getter?

C# will create the private variable so the byte-code is still correct, but for anyone reading your program there it is easier to understand what is going on.

Any time you can make code easier to read, even if there is syntactic sugar in the compiler, it is a win.

But, if you have to do any operation, such as check that the property is within a certain range, then, in C#3 you still need to write everything else out yourself.

The best practice is to just write it as you have in the question.

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