我正在尝试按照以下答案在派生类中强制使用特定的参数化构造函数:
使用上述答案中提供的示例,代码编译按预期失败。即使在修改代码以使其与我的相似之后,它仍然失败。我的实际代码虽然编译得很好。我不知道为什么会这样。
这是提供的答案中的修改示例(不会按预期编译):
public interface IInterface
{
void doSomething();
}
public interface IIInterface : IInterface
{
void doSomethingMore();
}
public abstract class BaseClass : IIInterface
{
public BaseClass(string value)
{
doSomethingMore();
}
public void doSomethingMore()
{
}
public void doSomething()
{
}
}
public sealed class DerivedClass : BaseClass
{
public DerivedClass(int value)
{
}
public DerivedClass(int value, string value2)
: this(value)
{
}
}
现在我的代码可以顺利编译:
public interface IMethod
{
Url GetMethod { get; }
void SetMethod(Url method);
}
public interface IParameterizedMethod : IMethod
{
ReadOnlyCollection<Parameter> Parameters { get; }
void SetParameters(params Parameter[] parameters);
}
public abstract class ParameterizedMethod : IParameterizedMethod
{
public ParameterizedMethod(params Parameter[] parameters)
{
SetParameters(parameters);
}
private Url _method;
public Url GetMethod
{
get
{
return _method;
}
}
public void SetMethod(Url method)
{
return _method;
}
public ReadOnlyCollection<Parameter> Parameters
{
get
{
return new ReadOnlyCollection<Parameter>(_parameters);
}
}
private IList<Parameter> _parameters;
public void SetParameters(params Parameter[] parameters)
{
}
}
public sealed class AddPackageMethod : ParameterizedMethod
{
public AddPackageMethod(IList<Url> links)
{
}
public AddPackageMethod(IList<Url> links, string relativeDestinationPath)
: this(links)
{
}
private void addDownloadPathParameter(string relativeDestinationPath)
{
}
private string generatePackageName(string destination)
{
return null;
}
private string trimDestination(string destination)
{
return null;
}
}
我删除了一些方法中的实现以使其尽可能简洁。作为旁注,我的实际代码可能在某些方面有所缺失。考虑那些在制品的部分。
更新 1/解决方案:
根据下面sstan 的回答,指出在此处使用关键字“params”的含义是我的代码的更正段落,这使得它按预期运行(编译失败):
public abstract class ParameterizedMethod : IParameterizedMethod
{
public ParameterizedMethod(Parameter[] parameters) // **'params' removed**
{
SetParameters(parameters);
}
// original implementation above
}