c# - 获取方法还是私有(private)属性(property)?

标签 c# .net

这只是一个口味问题,但我想听听您的一些意见(这也是为什么这个问题被标记为主观的原因)。

如果我有属性(property),说

private string _Text;
public string Text;
get
{
   object tmp = ViewState["Text"];
   if (tmp != null)
      _Text = Convert.ToString(tmp);
   return _Text;
}
set
{
   ViewState.Add("Text", value);
}

现在这是程序员可以通过设置一些自定义文本来指定的属性。然后将其映射到 UI 上的某些控件。然而,在默认情况下,控件的 Text 来自预定义的资源文件。所以在内部以更好的方式处理这个问题,我有一个中心点,我检查用户是否指定了“文本”属性(上图),如果是,则使用该数据,否则依赖于默认的资源文件。

那么你会采取什么方法呢?我有两个选择:
private string ResolvedText
{
   get
   {
      if(!string.IsNullOrEmpty(Text))
         return Text;
      else
         //return the one from the resource file
   }
}

或者把所有东西都放在一个方法中
public string GetResolvedText()
{
   if(!string.IsNullOrEmpty(Text))
      return Text;
   else
      //return the one from the resource file   
}

这个问题对你来说可能听起来很愚蠢,因为它真的是一个很小的区别。但我想知道这方面是否有一些约定。

谢谢

最佳答案

就个人而言,我会采用您的 GetResolvedText 方法的主体,并在属性中使用它,因此:

private string _Text;
public string Text
{
   get
   {
     if(string.IsNullOrEmpty(_Text))
        //return the one from the resource file  
     else
        return _Text;
   }

   set
   {
      _Text = value;
   }
}

这将管理字符串的所有责任集中到一个地方。类本身可以访问_Text在内部,如果它需要原始值。

关于c# - 获取方法还是私有(private)属性(property)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1286467/

相关文章:

c# - 如何清除文本文件内容c#

c# - Tulpep PopupNotifier 无法与计时器一起使用

.net - 调试与发布 dll 大小

.net - 获取 "on the wire"WCF 中消息的大小

c# - 在 Windows 10 上将 UWP Geolocation-API 与 Win32-Application 结合使用

javascript - 获取外键表数据

c# - ExecuteNonQuery 在 .NET 4.6.1 中永远挂起

.net - 什么是 Visual Studio 中引用属性的别名?

c# - 从具有多个零值的枚举中获取项目名称

.net - 芯片供应商是否提供任何 .Net JIT 支持?