zoukankan      html  css  js  c++  java
  • 带约束的泛型方法

    public interface IAccount
        {
            decimal Balance { get; set; }
            string Name { get; }
        }
    public class Account : IAccount
        {
            private decimal balance;
            public decimal Balance
            {
                get
                {
                    return balance;
                }
    
                set
                {
                    balance = value;
                }
            }
    
            public string Name
            {
                get
                {
                    throw new NotImplementedException();
                }
            }
        }
    private decimal _balance;
            public decimal Balance
            {
                get
                {
                    return _balance;
                }
    
                set
                {
                    _balance = value;
                }
            }
    
            public string Name
            {
                get
                {
                    throw new NotImplementedException();
                }
            }
        }
    class Program
        {
            static void Main(string[] args)
            {
                List<Account> list = new List<Account>() { new Account() { Balance = 5 }, new Account() { Balance = 5 } };
    
                decimal retvalue = Accumulate<Account>(list);
                Console.WriteLine(retvalue);
    
                List<Bccount> list1 = new List<Bccount>() { new Bccount() { Balance = 8 }, new Bccount() { Balance = 6 } };
                decimal retvalue1 = Accumulate<Bccount>(list1);
                Console.WriteLine(retvalue1);
    
                Console.ReadKey();
            }
    
            public static decimal Accumulate<T>(List<T> source) where T : IAccount
            {
                decimal sum = 0;
                foreach (T a in source)
                {
                    sum += a.Balance;
                }
                return sum;
            }
        }
  • 相关阅读:
    中间代码生成器-5-编译原理
    un-动物:老鼠
    un-动物:狗
    un-动物:猫
    un-动物:鹅
    un-动物:鸭子
    un-动物:鸡
    un-常见动物-动物:马
    un-常见动物-动物:骡
    un-常见动物-动物:牛
  • 原文地址:https://www.cnblogs.com/webczw/p/4761743.html
Copyright © 2011-2022 走看看