C#中如何做泛型类型限制

情况如下:
定义一个类aa;
另一个包含泛型方法类

 BB
{
有数个由aa派生的子类如a1 a2 a3
    public test <T>(<T> test)
    {
    xxxx;
    }
}

1.请问如何限制T使T仅是当前BB类中从aa中派生的子类a1 a2 a3中的一个。
2.若bb类可被继承,继承的类可继续派生a4 a5 a6.....能否不需重写test方法,即限制具有通用性。
非常感谢!!!

通过类做泛型约束 where
public class MyGenericClass where T:IComparable { }

C#中使用where子句限制泛型方法的泛型类型。
1.要求泛型类型实现一个接口或派生于某个基类;
2.不能定义必须由泛型类型实现的运算符。

TestMethodTTwo.cs:

[c-sharp] view plaincopy
using System;

using System.Collections.Generic;

namespace Magci.Test.Collections

{

//定义接口

public interface IAccount

{

string Name

{

get;

}

    decimal Balance     
    {     
        get;     
    }     
}     

public class Account : IAccount     
{     
    private string name;     
    public string Name     
    {     
        get    
        {     
            return name;     
        }     
    }     

    private decimal balance;     
    public decimal Balance     
    {     
        get    
        {     
            return balance;     
        }     
    }     

    public Account(string name, decimal balance)     
    {     
        this.name = name;     
        this.balance = balance;     
    }     
}     

public class Algorithm     
{     
    //声明泛型方法     
    public static decimal Total<TAccount>(IEnumerable<TAccount> e)     
        //使用where子句限制泛型类型     
        where TAccount : IAccount     
    {     
        decimal total = 0;     
        foreach (TAccount a in e)     
        {     
            total += a.Balance;     
        }     
        return total;     
    }     
}     

public class TestMethodTTwo     
{     
    public static void Main()     
    {     
        List<Account> accounts = new List<Account>();     
        accounts.Add(new Account("Magci", 9999.99m));     
        accounts.Add(new Account("Haha", 1241.33m));     
        accounts.Add(new Account("Heihei", 1551.2m));     
        accounts.Add(new Account("Kevin", 2643m));     

        //调用泛型方法     
        decimal total = Algorithm.Total(accounts);     
        Console.WriteLine("Total : {0:C}", total);     
    }     
}     

}