泛型交换方法

本文介绍了C#中的泛型使用,包括泛型方法、泛型约束和泛型委托的应用实例。通过具体代码展示了如何使用泛型来提高代码的复用性和灵活性,以及如何利用泛型委托进行更复杂的泛型操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

void swap<T>(ref T x,ref T y)
{
      T temp=x;
       x=y;
       y=temp;
}
static void Main()
{
      int x=3,y=4;
      swap<int>(ref x,ref y);

}

加上ref 关键字 就可以按址传递了,ref可出可进,out只进不出。都是按址传递;意思就是out传进方法里的时候,需要初始化;

foreach迭代:一般foreach迭代器需要有迭代的对象继承 IEnumerable<T>/IEnumerable ,而List 是继承 IEnumerable<T>的,因次可以进行foreach;迭代,比如要统计一个list里面的所有账目;

    public Interface IAccount
    {
     string Name{get;};decimal Balance{get;};
    }
   public class Account:IAccount
        {    //decimal 十进制的意思
            public string Name { get; }
            public decimal Balance{ get; private set; }
            public Account(string name, Decimal balance)
            {
                Name = name;
                Balance = balance;
            }

        }

public static class Algorithms<T> where T:IAccount
{
    public static decimal AccumulateSimple(IEnumerable<T> source)    
    {
       decimal sum=0;
        foreach(T a in source)
        {
            sum=a.Balance;
        }
        return sum;
    }
    //使用泛型委托 Func
    public static T2 Accumulate<T1,T2>(IEnumerable<T1> source,Func<T1,T2,T2> func)    
    {
       T2 sum= default(T2);//默认值为0/null
        foreach(T1 item in source)
        {
            sum+=func(item,sum);
        }
        return sum;
    }
}

static void main()
{
    var accounts = new List<Account>()
            {
                new Account("C",1500),

                new Account("S",2200),

                new Account("A",1800),

                new Account("m",2400),
            };
            decimal amount = Algorithms<Account>.AccumulateSimple(accounts);
        //调用 泛型方法
            decimal amount = Algorithms.Accumulate<Account,decimal>(accounts,(item,sum)=> sum+=item.Balance);
}

加了泛型约束 方便扩展;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值