我想允许继承,但禁止直接构造任何继承的类。相反,我想强制使用自定义方法New()
。
目标是确保继承类的每个实例都是其自身的透明代理。
在这种情况下,不可能创建构造函数private
或internal
. 否则,您不能再从程序集之外的类继承。
有什么优雅的方法可以解决这个问题吗?我目前的解决方案:
public abstract class Class<This> : MarshalByRefObject where This : Class<This>
{
private static bool ShouldThrowOnConstruction = true;
private static readonly object Lock = new object();
public static This New()
{
lock (Lock)
{
ShouldThrowOnConstruction = false;
var instance = (This)new ClassProxy<This>().GetTransparentProxy();
ShouldThrowOnConstruction = true;
}
return instance;
}
protected Class()
{
if (ShouldThrowOnConstruction)
{
throw new InvalidOperationException("Direct use of the constructor is forbidden. Use New() instead.");
}
}
}