C# 中的私有“设置" - 无法将我的大脑环绕在它周围 [英] Private 'set' in C# - having trouble wrapping my brain around it

查看:61
本文介绍了C# 中的私有“设置" - 无法将我的大脑环绕在它周围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多使用类似代码编写的示例代码(请原谅这是多么可怕的罐头):

I've seen a lot of example code written using something like (please forgive how horribly canned this is):

public class Test
{
   public object Thingy { get; private set; }
}

不幸的是,这些例子从来没有真正解释过为什么set"被设置为私有.所以,我只是想知道是否有一个好的、常见的例子来向我说明为什么会使用这样的东西.

Unfortunately, these kinds of examples never really explain why 'set' is set as private. So, I'm just wondering if there's a good, common example that will illustrate to me why something like this would be used.

我有点明白 - 除了设置该字段之外,还可以运行该属性来处理一些额外的逻辑.我只是对如何调用它以及为什么要使用这种方法而不是通用的 setter 方法感到困惑.

I sort of see it - the property can be run to process some extra logic in addition to setting that field. I'm just confused on how it would be invoked, and why this approach would be used rather than a generic setter method.

推荐答案

如果您有一个属性,除了您的类,您不希望任何人设置它.这对于数据库 id 很方便.内部类可以设置它,但您不希望其他任何人更改它.所以你可以给他们读权限,但不能写.

This would be if you have a property that you don't want anyone to set but your class. This can be handy with database id's. The internal class can set it but you wouldn't want anyone else changing it. So you can give them read access but not write.

关于这一点的另一点是,使用您在那里展示的内容有助于自动属性.不幸的是,对于自动属性,您无法仅指定 get 以避免公开暴露设置器,它只是设为私有.

One more point on this is that using what you showed there is helpful for automatic properties. Unfortunately with automatic properties you are unable to only specify get so to avoid exposing a setter publicly it is just made private.

只是想我会举一个例子.自动属性非常适合干净、简洁的代码.但是就像你展示的那样,你必须有 get 和 set 的限制.所以在像你展示的那样的属性之前:

Just thought I would throw in an example. Automatic properties are great for clean, terse code. But like you showed there is a limitation in that you have to have get and set. So before it was like this for a property like you showed:

public class Test
{
   private object thingy;
   public object Thingy
   {
      get { return thingy; }
   }
}

现在我们可以摆脱不需要的私有声明,但它需要两者.因此,请设为私有以解决该问题.

Now we can get rid of that unneeded private declaration but it requires both. So make private to get around that.

我知道这个解释有点矫枉过正,但我​​的脑海中不断出现不同的事情.

I know this was overkill on the explanation but different things kept popping in my head.

这篇关于C# 中的私有“设置" - 无法将我的大脑环绕在它周围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆