获取方法或私有财产?

Jur*_*uri 1 .net c#

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

如果我有房产,请说

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);
}
Run Code Online (Sandbox Code Playgroud)

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

那你采取什么方法?我有两个选择:

private string ResolvedText
{
   get
   {
      if(!string.IsNullOrEmpty(Text))
         return Text;
      else
         //return the one from the resource file
   }
}
Run Code Online (Sandbox Code Playgroud)

或者把所有东西放在方法中

public string GetResolvedText()
{
   if(!string.IsNullOrEmpty(Text))
      return Text;
   else
      //return the one from the resource file   
}
Run Code Online (Sandbox Code Playgroud)

这个问题对你来说可能听起来很愚蠢,因为它确实是一个微小的差异.但我想知道是否有一些约定.

谢谢

Ste*_*ham 6

就个人而言,我将采用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;
   }
}
Run Code Online (Sandbox Code Playgroud)

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