是否具有“代理特性”?好作风? [英] Are "proxy properties" good style?

查看:42
本文介绍了是否具有“代理特性”?好作风?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字符串属性的类,实际上是几个用分隔符连接的字符串。

I have a class with a string property that's actually several strings joined with a separator.

我想知道是否有像这样的代理属性是一种好形式此:

I'm wondering if it is good form to have a proxy property like this:

public string ActualProperty
{
    get { return actualProperty; }
    set { actualProperty = value; }
}

public string[] IndividualStrings
{
    get { return ActualProperty.Split(.....); }
    set 
    { 
            // join strings from array in propval .... ;
            ActualProperty = propval;
    }
}

我是否有忽略的风险?

推荐答案

似乎数组是真实数据,单字符串是一种方便。很好,但是我想说要注意诸如序列化和成员克隆之类的事情,它们将获取并设置两个可写属性。

Seems that the array is the real data, and the single-string stuff is a convenience. That's fine, but I'd say look out for things like serialization and memberwise cloning, which will get and set both writeable properties.

我想我会


  • 将数组保留为属性

  • 提供一个 GetJoinedString(字符串分隔符)方法。

  • 提供一个 SetStrings(字符串连接,字符串分隔符) Parse(字符串连接,字符串分隔符)方法。

  • keep the array as a property
  • provide a GetJoinedString(string seperator) method.
  • provide a SetStrings(string joined, string seperator) or Parse(string joined, string seperator) method.

实际上,字符串中的分隔符并不是真正的类的一部分,而是一个短暂的细节。明确引用它,例如,CSV应用程序可以传递逗号,制表符分隔的应用程序可以传递标签。这将使您的应用更易于维护。而且,它消除了为相同的实际数据使用两个getter和setter的麻烦问题。

Realistically, the seperator in the strings isn't really part of the class, but an ephemeral detail. Make references to it explicit, so that, say, a CSV application can pass a comma, where a tab-delimited app could pass a tab. It'll make your app easier to maintain. Also, it removes that nasty problem of having two getters and setters for the same actual data.

这篇关于是否具有“代理特性”?好作风?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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