只写属性或方法? [英] WriteOnly Property or Method?

查看:204
本文介绍了只写属性或方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个特定的场景,一个只写属性使更多的意义则方法?该方法的方法感觉对我来说更自然。

Is there a particular scenario where a WriteOnly property makes more sense then a method? The method approach feels much more natural to me.

什么是正确的做法?

使用属性

Public WriteOnly Property MyProperty As String
   Set(ByVal value as String)
      m_myField = value
   End Set
End Property

public string MyProperty
{
   set{ m_myField = value;}
}

使用方法:

Public Sub SetMyProperty(ByVal value as String)
   m_myField = value
End Sub

public void SetMyProperty(string value)
{
   m_myField = value;
}

修改 只是为了澄清我指的是只写属性。

EDIT Just to clarify I am referring to "WriteOnly" properties.

推荐答案

我觉得一个属性指示的东西,可以是只读或读/写。只写属性的行为并不明显,所以我避免造成他们。

I think a property indicates something that can be read-only or read/write. The behaviour of a write-only property is not obvious so I avoid creating them.

作为一个例子,设定值的列表中的一个视图下拉和访问所选择的项目:

As an example, setting a list of values in a drop-down on a view and accessing the selected item:

public interface IWidgetSelector
{
  void SetAvailableWidgets(string[] widgets);

  string SelectedWidget { get; set; }
}

更有意义比:

Makes more sense than:

public interface IWidgetSelector
{
  string[] AvailableWidgets { set; }

  string SelectedWidget { get; set; }
}

这篇关于只写属性或方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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