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<,>
类本身必须是公共(public)的(这意味着我不能在 Derived<,>
内部嵌套 Base<>
)。只有这样我才能返回 Derived<,>
来自静态Create
Base<>
中的方法.
这可能吗?
最佳答案
您可以使派生类的构造函数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
{
}
}
关于c# - 仅将构造函数公开给基类,可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16093448/