最近我發現自己越來越習慣於通過引用傳遞事物。我總是被教導說,通過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