.NET - 如何使一个类,使得只有一个其他特定的类可以实例化呢?
我想有以下设置:
class Descriptor
{
public string Name { get; private set; }
public IList<Parameter> Parameters { get; private set; } // Set to ReadOnlyCollection
private Descrtiptor() { }
public Descriptor GetByName(string Name) { // Magic here, caching, loading, parsing, etc. }
}
class Parameter
{
public string Name { get; private set; }
public string Valuie { get; private set; }
}
整个结构将在只读一次从XML文件加载。我想使它如此,只有描述符类实例化一个参数。
The whole structure will be read-only once loaded from an XML file. I'd like to make it so, that only the Descriptor class can instantiate a Parameter.
这样做将是使一个 IParameter
接口,然后让参数
类私有的描述符的一种方法一流的,但在现实世界中使用的参数将有几个属性,我想避免重新定义他们的两倍。
One way to do this would be to make an IParameter
interface and then make Parameter
class private in the Descriptor class, but in real-world usage the Parameter will have several properties, and I'd like to avoid redefining them twice.
这在某种程度上可能吗?
Is this somehow possible?
使它成为实现一个特定的接口的私人嵌套类。然后,只有外类可以实例化,但是任何人都可以使用它(通过接口)。例如:
Make it a private nested class that implements a particular interface. Then, only the outer class can instantiate it, but anyone can consume it (through the interface). Example:
interface IParameter
{
string Name { get; }
string Value { get; }
}
class Descriptor
{
public string Name { get; private set; }
public IList<IParameter> Parameters { get; private set; }
private Descriptor() { }
public Descriptor GetByName(string Name) { ... }
class Parameter : IParameter
{
public string Name { get; private set; }
public string Value { get; private set; }
}
}
如果你真正的必须避免了接口,可以创建具有的所有属性,但声明了一个受保护的构造一个公共抽象类。然后,您可以创建一个私有的嵌套类,它继承了只能由外部类中创建并返回它的实例为基本类型的公共抽象。例如:
If you really must avoid the interface, you can create a public abstract class that has all of the properties but declares a protected constructor. You can then create a private nested class that inherits from the public abstract that can only be created by the outer class and return instances of it as the base type. Example:
public abstract AbstractParameter
{
public string Name { get; protected set; }
public string Value { get; protected set; }
}
class Descriptor
{
public string Name { get; private set; }
public IList<AbstractParameter> Parameters { get; private set; }
private Descriptor() { }
public Descriptor GetByName(string Name) { ... }
private class NestedParameter : AbstractParameter
{
public NestedParameter() { /* whatever goes here */ }
}
}