【发布时间】:2012-12-28 19:38:37
【问题描述】:
我不确定这是否是无效的做法;或良好的做法。我不知所措的原因是我应该使用属性而不是局部变量吗?
我的推理和目标;是对本地磁盘驱动器的非常基本的检测。
我想指出一些事情:
- 我没有选择
boolean value,因为我希望能够调用这个类来返回驱动器路径。因此从方法中检索到的名称;在某些派生类中可以是Path Combined。
我的例子:
public class Drive
{
// Variable:
public string nameOfDrive;
public Drive()
{
// Call Method.
DriveName();
}
public string DriveName()
{
DriveInfo [] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
// Verify Valid 'C:' is Present.
if (d.Name == @"C:")
{
// Set Name:
nameOfDrive = d.Name;
// Return Result.
return d.Name;
}
}
// Exception:
throw new Exception("Unable to locate the C: Drive... Please map the correct drive.");
}
}
/*
* The above method and class contains a verification
* for the 'C:' Drive. Once the items are validated;
* it will create a return variable for the 'C:'.
* Otherwise it will throw an Exception.
*/
现在我不确定什么是更好的做法。我应该使用属性而不是public string nameOfDrive。还是我真的很遥远-这不是返回可在其他类中使用的值的最佳方法吗?还是直接引用成员变量是不好的做法?
第二个例子:
public class Drive
{
private string nameOfDrive;
public string NameOfDrive
{
get { return nameOfDrive; }
}
public Drive()
{
// Call Method.
DriveName();
}
public string DriveName()
{
// Obtain Drive Information:
DriveInfo [] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
// Verify Valid 'C:' is Present.
if (d.Name == @"C:")
{
// Set Name:
nameOfDrive = d.Name;
// Return Result.
return d.Name;
}
}
// Exception:
throw new Exception("Unable to locate the C: Drive... Please map the correct drive.");
}
}
/*
* The above method and class contains a verification
* for the 'C:' Drive. Once the items are validated;
* it will create a return variable for the 'C:'.
* Otherwise it will throw an Exception.
*/
这样它就被标记为只读并确保它从方法中读取正确的值?
更新:
感谢您的回答;但是为什么这是更好的做法?
- 对安全有好处吗?
- 更整洁?
- 更灵活
是什么使它成为更好的解决方案;这就是我试图理解的。
【问题讨论】:
-
您确实需要从这些示例中减少代码膨胀。我们不需要看到你的使用、命名空间,我们不需要所有的空格、区域和冗余的 cmets 等。特别是在比较两个代码 sn-ps 时,当所有这些不相关时,更难看出差异杂乱无章的排序虽然。即使您将所有这些都保留在实际代码中,也要在将其发布到此处之前对其进行过滤。
-
@Servy 我修好了。此外,无论是否有示例代码,您的代码中都不需要 20 个空行,也不需要随机无意义的区域和“自定义”注释文档约定。您可能想将您的一些代码带到codereview.stackexchange.com,以了解有关您的编码风格有什么问题的更多信息