[英]Can't enforce the use of base constructor of an abstract class into derived class
我试图在我的派生类中强制使用特定的参数化构造函数,如下面的答案所示:
使用上面答案中提供的示例,代码编译按预期失败。 即使在修改代码以使其与我的相似之后,它仍然会失败。 我的实际代码虽然编译得很好。 我不知道为什么会这样。
以下是提供的答案(不会按预期编译)的修改示例:
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;
}
}
我删除了一些方法中的实现,以尽可能简洁。 作为旁注,我的实际代码可能缺乏区域。 考虑这些部分WIP。
更新1 /解决方案:
根据sstan的回答,下面指出使用关键字'params'的含义是我的代码的更正通道,使其行为符合预期(编译失败):
public abstract class ParameterizedMethod : IParameterizedMethod
{
public ParameterizedMethod(Parameter[] parameters) // **'params' removed**
{
SetParameters(parameters);
}
// original implementation above
}
以下构造函数尝试在没有任何参数的情况下调用基类的构造函数。
public AddPackageMethod(IList<Url> links)
{
}
好吧,只是因为params
关键字, 可以在没有任何参数的情况下调用基类的构造函数。 所以编译得很好。
public ParameterizedMethod(params Parameter[] parameters)
{
SetParameters(parameters);
}
仅用于测试,如果删除params
关键字,从而强制传递参数,则代码将无法编译,就像您期望的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.