最近、私は自分自身が参照によって物事を渡す習慣にますます入り込んでいることに気づきました。オブジェクトに影響を与える可能性のあるものを追跡するのは難しいため、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;
}