Delphi中是否有类似C#的属性简化写法?
Delphi中类似C#的简洁属性写法
Delphi确实提供了类似C#的属性简化写法,不同版本的支持程度不同,以下是对应场景的实现方式:
1. 无验证逻辑的自动属性(Delphi XE3及以上)
如果不需要额外的参数验证或逻辑,直接使用自动属性即可,Delphi会自动生成后台字段,无需手动定义:
public property OpportunityNr: string read write;
2. 带验证逻辑的表达式属性(Delphi 10.3 Rio及以上)
对于需要像你示例中那样的非空验证逻辑,从Delphi 10.3开始支持将get/set逻辑直接内嵌在属性定义中,无需单独编写GetXXX和SetXXX方法:
private FOpportunityNr: string; public property OpportunityNr: string read function: string begin if SpecialStrUtils_13.IsBlankStr(FOpportunityNr) then raise Exception.CreateFmt('OPPORTUNITY NUMBER not set', []); Result := FOpportunityNr; end write procedure(const Value: string) begin if SpecialStrUtils_13.IsBlankStr(Value) then raise Exception.CreateFmt('OPPORTUNITY_NR cannot be empty', []); FOpportunityNr := Value; end;
3. 更简洁的箭头表达式语法(Delphi 10.4 Sydney及以上)
从Delphi 10.4开始,支持类似C#的=>箭头表达式,进一步简化代码:
private FOpportunityNr: string; public property OpportunityNr: string read => (if SpecialStrUtils_13.IsBlankStr(FOpportunityNr) then raise Exception.CreateFmt('OPPORTUNITY NUMBER not set', []) else FOpportunityNr) write => (if SpecialStrUtils_13.IsBlankStr(Value) then raise Exception.CreateFmt('OPPORTUNITY_NR cannot be empty', []) else FOpportunityNr := Value);
这种写法和你提供的C#代码逻辑完全一致,且无需拆分单独的方法,代码紧凑性已经非常接近C#的实现。
内容的提问来源于stack exchange,提问作者Paul Sinnema
相关产品推荐
相关产品推荐

