可能的话,只向基类公开构造函数
本文关键字:基类 构造函数 | 更新日期: 2023-09-27 18:10:01
public class Base<S>
{
public static Derived<S, T> Create<T>()
{
return new Derived<S, T>(); //if not public, I wont get it here.
}
}
public class Derived<S, T> : Base<S>
{
public Derived() //the problem, dont want it public
{
}
}
这是我得到的基本结构。
要求:
1)我不希望Derived<,>
的实例被构造调用Derived<,>
类,无论是通过构造函数或静态方法。我希望它只通过Base<>
创建。所以这是:
public class Derived<S, T> : Base<S>
{
Derived()
{
}
public static Derived<S, T> Create()
{
return new Derived<S, T>();
}
}
2) Derived<,>
类本身必须是公共的(这意味着我不能在Base<>
内部私有嵌套Derived<,>
)。只有这样,我才能从Base<>
中的静态Create
方法返回Derived<,>
。
有可能吗?
您可以使派生类的构造函数internal
如
public class Base<S>
{
public static Derived<S, T> Create<T>() // visible externally
{
return new Derived<S, T>();
}
}
public class Derived<S, T> : Base<S>
{
internal Derived() // not visible outside the current assembly
{
}
}
反思!
void Main()
{
Derived dr = Base.GetDerived<Derived>();
}
public class Base
{
public int ID { get; set; }
public Base()
{
}
public static T GetDerived<T>() where T : Base
{
T toReturn = (T)typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null).Invoke(null);
return toReturn;
}
}
public class Derived : Base
{
private Derived()
{
}
}
我将声明一个公共接口,并在Base
中实现私有:
public class Base<S>
{
public static IFoo<S, T> Create<T>()
{
return new Derived<T>(); //if not public, I wont get it here.
}
// Only generic in T, as we can use S from the containing class
private class Derived<T> : Base<S>, IFoo<S, T>
{
public Derived()
{
...
}
}
}
public interface IFoo<S, T>
{
// Whatever members you want
}
我这样实现了我的要求:
public abstract class Base<S>
{
public static Derived<S, T> Create<T>()
{
return new ReallyDerived<S, T>();
}
class ReallyDerived<T> : Derived<S, T>
{
public ReallyDerived()
{
}
}
}
public abstract class Derived<S, T> : Base<S>
{
}