gpt4 book ai didi

c# - 如果构造函数具有初始值设定项,那么构造函数在 C# 中需要一个主体是否有原因?

转载 作者:行者123 更新时间:2023-11-30 12:23:21 24 4
gpt4 key购买 nike

让我烦恼的是我必须拥有它们,例如考虑案例

public class IsEquipmentAvailable : Specification<Equipment>
{
public IsEquipmentAvailable() : base(equipment => equipment.CartEquipments
.All(o => o.RentState == RentState.Done))
}

但是,我不允许写这个,因为我需要添加 {},在 c# 中,至少有 2 行样板代码不执行任何操作。如果我想支持定向表达式图链调用或只是从表达式实例化元素,那就更糟了。

public class IsEquipmentAvailable : Specification<Equipment>
{
public IsEquipmentAvailable(Expression<Func<Equipment, bool>> expression)
: base(expression)
{
}

public IsEquipmentAvailable(ISpecification<Equipment> specification)
: base(specification)
{
}

public IsEquipmentAvailable() : base(equipment => equipment.CartEquipments
.All(o => o.RentState == RentState.Done))
{
}
}

我的函数式编程方面因为无知而笑,因为他不知道。有时事情之所以如此,是有正当理由的,所以我想知道这背后的原因。

最佳答案

language确实允许遗漏 - 恰好与我们正在寻找的那个相反(10.11.1):

All instance constructors (except those for class object) implicitly include an invocation of another instance constructor immediately before the constructor-body

和:

If an instance constructor has no constructor initializer, a constructor initializer of the form base() is implicitly provided. Thus, an instance constructor declaration of the form

C(...) {...}

is exactly equivalent to

C(...): base() {...}

因此,具有初始化器的构造函数也不异常(exception),因为根据语言规范,所有构造器实际上都具有初始化器。


此外,这里的语言非常一致,当您考虑时 - 唯一允许您完全省略方法主体的地方就是您所在的地方,特别是禁止提供主体 - 如评论中提到的 extern 构造函数,或 abstract 方法。在其他任何地方,您都必须提供一个主体,即使您选择使其为空。

关于c# - 如果构造函数具有初始值设定项,那么构造函数在 C# 中需要一个主体是否有原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37314728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com