C# 8.0 特性与微服务构建全解析
1. C# 8.0 默认接口方法
在 C# 8.0 中,开发者可以在接口中添加带有方法体的方法。以往,我们必须在后续的类中显式编写接口方法的功能。而现在,默认接口方法让我们在后续类调用这些方法时能获得预定义的结果。
示例代码
public interface IProduct
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string ProductDesc() => $"Book:{Name} has Price:{Price}";
}
public class Product : IProduct
{
public Product(int id, string name, decimal price)
{
Id = id;
Name = name;
Price = price;
}
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
代码解释
-
IProduct
接口包含了Id
、Name