最近我发现自己越来越习惯于通过引用传递事物。我总是被教导说,通过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
和SetValue
都在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;
}
你没有'ViewState.GetValue(...);'此刻的检查和lazy-instansiation?为什么你不能在你的Foobar类中使用泛型方法,而是为你做这个工作? – Default 2012-04-17 09:24:29
这对我来说看起来有点奇怪。为什么要将相同的对象存储两次,一次存储在__ __ ___中,一次存储在'this.ViewState [“MyObject”]中?第一个'get'根本没有任何回报,你总是会实例化一个新的对象,不管你是否使用它。 – martinstoeckli 2012-04-17 09:24:54
可能的重复:http://stackoverflow.com/questions/570471/whats-so-bad-about-ref-parameters – Default 2012-04-17 09:29:13