file partial class PartialPropertyClass { public partial int Num { get; set; } } file partial class PartialPropertyClass { private int _num = 1; public partial int Num { get => _num; set => _num = value; } } file partial struct PartialPropertyStruct { [DisplayName("Number")] public partial int Num { get; } } file partial struct PartialPropertyStruct { [JsonPropertyName("num")] public partial int Num => 2; }partial property 既可以用于 class 也可以用于 struct
CS9250: a partial property cannot be automatically implemented
CS9252: Property accessor 'PartialPropertyClass.Num.set' must be implemented because it is declared on the definition part
partial property 只能一处声明,一处实现,不能两个地方定义声明或者两个地方定义实现,也会导致编译错误
file partial class PartialIndexer { public partial string this[int index] { get; } } // 堆代码 duidaima.com file partial class PartialIndexer { public partial string this[int index] { get => index.ToString(); } }正则表达式 source generator 使用示例如下:
[GeneratedRegex(@"^1[1-9]\d{9}$")] private static partial Regex PhoneRegex(); [GeneratedRegex(@"^1[1-9]\d{9}$")] private static partial Regex PhoneNumberRegex { get; } var phone = "12312341234"; Console.WriteLine(PhoneRegex().IsMatch(phone)); Console.WriteLine(PhoneNumberRegex.IsMatch(phone));二者输出的结果是一样的,只是一个正则是一个 method,另外一个是 property。
file partial class PartialPropertyClass { public partial int Num { get; set; } } file partial class PartialPropertyClass { private int _num; [Display(Name = "Number")] public partial int Num { get => _num; set => _num = value; } }在有了 field keyword 支持之后,我们也可以做一个简化
file partial class PartialPropertyClass { public partial int Num { get; set; } } file partial class PartialPropertyClass { [Display(Name = "Number")] public partial int Num { get => field; set => field = value; } }最后再留一个问题
/// <summary> /// My type /// </summary> partial class C { /// <summary>Definition part comment</summary> /// <returns>Return value comment</returns> public partial int Prop { get; set; } /// <summary>Implementation part comment</summary> public partial int Prop { get => 1; set { } } }
这样的声明和实现上都有文档注释,生成的 xml 文档最后会是什么样子呢?感兴趣的朋友可以自己试一下。