我有一堆扩展方法,可以将我的实体转换DTOs
为如下形式。
public static LocationDto? ToDto(this Location? @this)
{
if (@this == null) return null;
return new LocationDto
{
Id = @this.Id,
Text = @this.Name,
ParentId = @this?.Parent?.Id,
};
}
这里的问题是,如果传递不为null的实体,仍然会收到可为null的实体,并且无法定义a,public static LocationDto ToDto(this Location @this)
因为它们将被编译为相同的方法。
另外,我不喜欢!
在打电话时使用它。所以以下不是我的答案。
Location entity = AMethod();
LocationDto dto = entity.ToDto()!;
是否有属性或语法告诉编译器此方法的行为?有点像:
public static [NullableOnlyIfInputIsNull] LocationDto? ToDto(this Location? @this)
您要求的属性是NotNullIfNotNullAttribute
该属性接受用于推断无效性的参数的名称。
您的情况如下所示:
using System.Diagnostics.CodeAnalysis;
// ...
[return:NotNullIfNotNull("this")]
public static LocationDto? ToDto(this Location? @this)
{
// Your code here
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句