最近我发现自己越来越养成通过引用传递事物的习惯。我一直被教导通过 ref 传递“通常”是一个坏主意,因为跟踪可能影响您的对象的东西比较棘手,所以我想发布一个问题:“通过引用传递的缺点是什么? '
我最近通过引用传递的一个示例是视图状态中的惰性实例化对象。在我的代码隐藏中,我有一个带有公共属性的私有字段,它使用了一个辅助方法。目前的实现如下:
ASPX 代码隐藏
/// <summary>
/// Private field member for MyObject
/// </summary>
private Foobar _myObject = null;
/// <summary>
/// Gets or sets the current object
/// </summary>
public Foobar MyObject
{
get
{
return this.ViewState.GetValue("MyObject", new Foobar(), ref this._myObject);
}
set
{
this.ViewState.SetValue("MyObject", value, ref this._myObject);
}
}
这旨在替换if
针对类中的字段和惰性实例化对象的大量重复分配检查。例如,如果没有辅助类,它将类似于。
/// <summary>
/// Private field member for MyObject
/// </summary>
private Foobar _myObject = null;
/// <summary>
/// Gets or sets the current object
/// </summary>
public Foobar MyObject
{
get
{
if (this._myObject != null)
{
return this._myObject;
}
var viewStateValue = this.ViewState["MyObject"];
if (viewStateValue == null || !(viewStateValue is Foobar))
{
this.ViewState["MyObject"] = new Foobar();
}
return this._myObject = (Foobar)this.ViewState["MyObject"];
}
set
{
this._myObject = value;
this.ViewState["MyObject"] = value;
}
}
两个代码片段都实现了相同的目标。第一种方法是集中一切,这是一件好事,但是它是通过引用传递的,在这种情况下我不确定这是一个好主意吗?
非常感谢任何建议和/或经验。
编辑GetValue
andSetValue
是 ViewState 上的扩展方法
。下面提供了代码。
/// <summary>
/// Gets a value from the current view state, if the type is correct and present
/// </summary>
public static T GetValue<T>(this StateBag source, string key, T @default)
{
// check if the view state object exists, and is of the correct type
object value = source[key];
if (value == null || !(value is T))
{
return @default;
}
// return the object from the view state
return (T)source[key];
}
/// <summary>
/// Sets the key value within the view state
/// </summary>
public static void SetValue<T>(this StateBag source, string key, T value)
{
source[key] = value;
}
/// <summary>
/// Gets a value from the reference field helper, or the current view state, if the type is correct and present
/// </summary>
/// <returns>Returns a strongly typed session object, or default value</returns>
public static T GetValue<T>(this StateBag source, string key, T @default, ref T fieldHelper)
{
return fieldHelper != null ? fieldHelper : fieldHelper = source.GetValue(key, @default);
}
/// <summary>
/// Sets the key value within the view state and the field helper
/// </summary>
/// <param name="value">The value</param>
public static void SetValue<T>(this StateBag source, string key, T value, ref T fieldHelper)
{
source[key] = value;
fieldHelper = value;
}