如何使用不带参数的带参数的构造函数
How to use constructor with parameters from one without parameters
我有一个控制器,它带有一个 DbContext
和一个不带的控制器。即:
public CalendarController()
{
var db = new DbContext();
CalendarController(db); // <= Not allowed
}
public CalendarController(IDbContext db)
{
_calendarManager = new CalendarManager(db);
_userManager = new UserManager(db);
_farmingActionManager = new FarmingActionManager(db);
_cropManager = new CropManager(db);
}
不幸的是,上面的 CalendarController(db)
行给出了一个错误:
Expression denotes a 'type', where a 'variable', 'value' or 'method group` was expected
是否可以从一个构造函数调用另一个构造函数?我不想复制所有代码。
你必须像这样链接到构造函数:
public CalendarController() : this(new DbContext())
{
}
这是在同一个 class 中链接到 any 构造函数的语法 - 它不一定是从无参数构造函数到参数化构造函数,尽管它必须是不同的:)
请注意,这出现在构造函数的主体之前,因此您不能先做任何其他事情,尽管您可以调用静态方法来计算另一个构造函数的参数。但是,您不能使用 instance 方法或属性。所以这没关系:
public Foo() : this(GetDefaultBar())
{
}
public Foo(int bar) { ... }
private static int GetDefaultBar() { ... }
但这不是:
public Foo() : this(GetDefaultBar())
{
}
public Foo(int bar) { ... }
private int GetDefaultBar() { ... }
链接到基础 class 中的构造函数的语法类似:
public Foo() : base(...)
如果您没有指定 : base(...)
或 : this(...)
,编译器会隐式地为您添加一个 : base()
。 (这不一定链接到无参数构造函数;它可以有可选参数。)
我有一个控制器,它带有一个 DbContext
和一个不带的控制器。即:
public CalendarController()
{
var db = new DbContext();
CalendarController(db); // <= Not allowed
}
public CalendarController(IDbContext db)
{
_calendarManager = new CalendarManager(db);
_userManager = new UserManager(db);
_farmingActionManager = new FarmingActionManager(db);
_cropManager = new CropManager(db);
}
不幸的是,上面的 CalendarController(db)
行给出了一个错误:
Expression denotes a 'type', where a 'variable', 'value' or 'method group` was expected
是否可以从一个构造函数调用另一个构造函数?我不想复制所有代码。
你必须像这样链接到构造函数:
public CalendarController() : this(new DbContext())
{
}
这是在同一个 class 中链接到 any 构造函数的语法 - 它不一定是从无参数构造函数到参数化构造函数,尽管它必须是不同的:)
请注意,这出现在构造函数的主体之前,因此您不能先做任何其他事情,尽管您可以调用静态方法来计算另一个构造函数的参数。但是,您不能使用 instance 方法或属性。所以这没关系:
public Foo() : this(GetDefaultBar())
{
}
public Foo(int bar) { ... }
private static int GetDefaultBar() { ... }
但这不是:
public Foo() : this(GetDefaultBar())
{
}
public Foo(int bar) { ... }
private int GetDefaultBar() { ... }
链接到基础 class 中的构造函数的语法类似:
public Foo() : base(...)
如果您没有指定 : base(...)
或 : this(...)
,编译器会隐式地为您添加一个 : base()
。 (这不一定链接到无参数构造函数;它可以有可选参数。)