シングルトンのような静的メンバーを持つクラスがあるとします。 私はまた、そのクラスの構築を許可します。 コンシューマが既知の引数を使用してコンストラクトを作成する場合、新しいコンストラクションの代わりに静的なメンバを返したいと思います。コンストラクタ内の静的クラスメンバーの 'this'ポインタの切り替え
以下は、ポイントを示す非コンパイルのコード例です。 本来、クラスはConstruct
メソッドのように構築されていますが、クラスのコンシューマが既存のnew MyClass(0)
呼び出しを書き直すことを強いられないようにしたいと思います。
これは可能ですか?
public class MyClass
{
public static readonly MyClass Zero = new MyClass(0);
private int n;
public static MyClass Construct(int n)
{
MyClass self = new MyClass(0, true); //the bool just helps with referencing
ReplaceIfZero(ref self);
return self;
}
public MyClass(int n, bool x) //the bool is just so i can reference it in this example
{
this.n = n;
}
public MyClass(int n)
{
this.n = n;
ReplaceIfZero(ref this);
// Error CS1605 Cannot pass 'this' as a ref or out argument because it is read - only
}
ReplaceIfZero(ref MyClass myclass)
{
if(Zero.Equals(myclass))
{
myclass = Zero;
}
}
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj) || ((obj is MyClass) && n.Equals((obj as MyClass).n));
}
}
'new'演算子の結果を変更することはできません。パブリックコンストラクタを削除し、クライアントに 'MyClass.Create'のようなpublic static factoryメソッドを使用させる必要があります –
@IvanStoev:あなたのコメントから回答を作成する必要があります – Falanwe