正在使用ref
是不好的编程习惯吗?我正在对我的旧代码进行一些重构,这些代码实际上经常使用 ref 。我已使用 Microsoft 所有规则集打开代码分析,并且规则规定“不要通过引用传递类型”
原因:公共(public)类型中的公共(public)或 protected 方法具有 ref 参数,该参数采用基本类型、引用类型或不是内置类型之一的值类型。
为什么它真的很糟糕?我可以在我的私有(private)方法或内部方法中使用它们吗?在私有(private)/内部方法中使用 ref 是否是良好的编程实践?
编辑: 这是一些示例,
public void DoAutoScrollReverse(Rectangle rectangle, int xPosition, int yPosition,
ref int deltaX, ref int deltaY)
{
}
public bool GetPointCoords(Graphics g, Point pMouse, DisplayBlock2D aBlock,
ref Point3MD pt, ref DisplayPoint2D 2dPoint, ref double gapPos)
{
}
这些函数内部发生的事情是它们正在被初始化、设置或其他什么。
更新:为什么我要使用 ref?其实我不是。我需要重构它的旧代码。我摆脱了一些方法,但像第二个例子中的复杂函数我不能这样做。有一个函数返回 bool (告诉操作成功与否)并且有 3 个不同对象的引用值。我应该在这里做什么?将其设置为私有(private)/内部(在私有(private)/内部使用 ref 是良好的做法吗?)
最佳答案
我认为除非确实有必要,否则最好不要使用 ref。如果可以用其他方法更改局部变量,则可能会导致难以检测的错误。
您的示例可以轻松重写,因此您不再需要使用 ref。
public void DoAutoScrollReverse(Rectangle rectangle, int xPosition, int yPosition,
ref int deltaX, ref int deltaY)
{
}
创建一个小类:
public class Delta
{
int X { get; set; }
int Y { get; set; }
}
没有引用:
public Delta DoAutoScrollReverse(Rectangle rectangle, int xPosition, int yPosition)
{
return new Delta(deltaX, deltaY);
}
现在,您正在返回以及您正在返回的内容也更加清楚。
关于c# - 使用 ref - 良好的编程实践与否,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17780307/