C# Can';t在派生类中强制使用抽象类的基构造函数
我试图在我的派生类中强制使用特定的参数化构造函数,如下所示: 使用上述答案中提供的示例,代码编译如预期的那样失败。即使在修改代码以使其类似于我的代码之后,它仍然失败。但我的实际代码编译得很好。我不知道这是为什么 下面是所提供答案的修改示例(不会按预期编译): 现在,我的代码可以顺利编译:C# Can';t在派生类中强制使用抽象类的基构造函数,c#,inheritance,constructor,default-constructor,enforcement,C#,Inheritance,Constructor,Default Constructor,Enforcement,我试图在我的派生类中强制使用特定的参数化构造函数,如下所示: 使用上述答案中提供的示例,代码编译如预期的那样失败。即使在修改代码以使其类似于我的代码之后,它仍然失败。但我的实际代码编译得很好。我不知道这是为什么 下面是所提供答案的修改示例(不会按预期编译): 现在,我的代码可以顺利编译: public interface IMethod { Url GetMethod { get; } void SetMethod(Url method); } public interfa
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;
}
}
下面的构造函数尝试在没有任何参数的情况下调用基类的构造函数
public AddPackageMethod(IList<Url> links)
{
}
仅为了测试,如果您删除
params
关键字,从而强制传递参数,那么您的代码将无法编译,正如您所期望的那样。您完全正确。我从未想到过使用“params”的含义。感谢您快速交付该现场解决方案。您确切指的是哪一部分?不是问题正文,而是标签!;)哦,你说得对。我一定是在选择菜单时意外单击了错误的标记。谢谢你指出这一点。我纠正了那个错误
public abstract class ParameterizedMethod : IParameterizedMethod
{
public ParameterizedMethod(Parameter[] parameters) // **'params' removed**
{
SetParameters(parameters);
}
// original implementation above
}
public AddPackageMethod(IList<Url> links)
{
}
public ParameterizedMethod(params Parameter[] parameters)
{
SetParameters(parameters);
}