当前位置:网站首页>. Net interface can be implemented by default

. Net interface can be implemented by default

2022-07-07 03:38:00 Sky watching houses

from .NET Core 3.0 Upper C# 8.0 Start , You can define implementations when you declare interface members . The most common solution is to safely add members to interfaces that have been published and used by countless clients .

Example :

 internal interface ICustomer
    {
    
        IEnumerable<IOrder> PreviousOrders {
     get; }

        DateTime DateJoined {
     get; }
        DateTime? LastOrder {
     get; }
        string Name {
     get; }
        IDictionary<DateTime, string> Reminders {
     get; }

    }
    
  internal interface IOrder
    {
    
        DateTime Purchased {
     get; }
        decimal Cost {
     get; }
    }

C# Two common interfaces in . Then came the new feature .

 internal interface ICustomer
    {
    
        IEnumerable<IOrder> PreviousOrders {
     get; }

        DateTime DateJoined {
     get; }
        DateTime? LastOrder {
     get; }
        string Name {
     get; }
        IDictionary<DateTime, string> Reminders {
     get; }

        // Version 1:
        public decimal ComputeLoyaltyDiscountVersionOne()
        {
    
            DateTime TwoYearsAgo = DateTime.Now.AddYears(-2);
            if ((DateJoined < TwoYearsAgo) && (PreviousOrders.Count() > 10))
            {
    
                return 0.10m;
            }
            return 0;
        }

        // Version 2:
        public static void SetLoyaltyThresholds(
            TimeSpan ago,
            int minimumOrders = 10,
            decimal percentageDiscount = 0.10m)
        {
    
            length = ago;
            orderCount = minimumOrders;
            discountPercent = percentageDiscount;
        }
        private static TimeSpan length = new TimeSpan(365 * 2, 0, 0, 0); // two years
        private static int orderCount = 10;
        private static decimal discountPercent = 0.10m;

        public decimal ComputeLoyaltyDiscountVersionTwo()
        {
    
            DateTime start = DateTime.Now - length;

            if ((DateJoined < start) && (PreviousOrders.Count() > orderCount))
            {
    
                return discountPercent;
            }
            return 0;
        }

        // Another way 
        public decimal ComputeLoyaltyDiscount() => DefaultLoyaltyDiscount(this);
        protected static decimal DefaultLoyaltyDiscount(ICustomer c)
        {
    
            DateTime start = DateTime.Now - length;

            if ((c.DateJoined < start) && (c.PreviousOrders.Count() > orderCount))
            {
    
                return discountPercent;
            }
            return 0;
        }

    }```

原网站

版权声明
本文为[Sky watching houses]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062022577616.html