简体   繁体   中英

C# method with multiple generic parameters

I am trying to build a generic method and four classes that implement IDetail . Each class has a collection of a classes that implement ITaxes . I want to build a generic method that will allow me to access the collection of each class.

Something like this:

public void UpdateCollection<T,I>(T Detail,Taxes TaxesList ) where T:IDetail where I:Itaxes
{
   foreach( Taxes  tax in TaxesList)
   {
       Detail.I.Add(tax);
   } 
} 

I want to access the property of type I in type T . How can I do that? It is possible? Do I need to write one method for each class?

Ideally you'd modify your IDetail interface to include the list of ITaxes objects as a part of that interface. You could use explicit interface implementation if you want the named property that is exposed publicly to have a different name for each detail.

If that isn't possible, or doesn't make sense for other reasons, then your best bet is probably to have this method accept a Func<T, I> parameter to this method. The user can then provide a method to allow you to extract the required list from each T object:

public void UpdateCollection<T, I>(T Detail, Taxes TaxesList, Func<T, I> taxSelector)
    where T : IDetail
    where I : Itaxes
{
    I taxList = taxSelector(Detail);
    foreach (Taxes tax in TaxesList)
    {
        taxList.Add(tax);
    }
}

The caller than can use a lambda to define the appropriate property for that object.

Create a third interface which exposes the commonality of what you seek. In partial classes (if generated) subscribe to the interface and then within the generic method accept only that interface and process accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM