These are the 2 sets of activities :
//#1
List<object> AFilterObject = A_List.SelectedList;
List<A> AFilters = new List<A>();
foreach (Aitem in AFilterObject )
{
//Do activity X
}
//#2
List<object> BFilterObj = B_List.SelectedList;
List<B> payopFilters = new List<B>();
foreach (B item in BFilterObj )
{
//Do same activity X }
As you can see both the set of activities are common except for the type involved. How can I write a method with 2 parameters - filterObject, Type - so that I can use this method in a common manner?
To make myself clearer, the final objective is:
CommonMethod(List<object> x, Type y???) { //cast x to type y then do some stuff }
//so that I can call
CommonMethod(BFilterObj ,B);
//or
CommonMethod(AFilterObj ,A);
Use a generic method:
public void ApplyFilters<T>(List<object> x)
{
...
}
You may need to apply some constraints to T so that you can do what you need to in the method. For example:
public void ApplyFilters<T>(List<object> x)
where T : class. ISomeInterface
{
...
}
You would then call it by specifying the type as a type argument :
ApplyFilters<A>(AFilterObj);
ApplyFilters<B>(BFilterObj);
If you don't know the type until execution time, that becomes somewhat harder - you have to call the method with reflection. Let me know if this is the case - but you don't want to do that unless you really have to.
If they have a common interface or base type, you can do this:
void DoActivities<TItem>(IList<TItem> filterObject) where TItem : SomeBaseType
{
foreach (SomeBaseType item in filterObject)
{
item.DoActivity(/* ... */);
}
}
If they don't have anything in common, you could do this:
void DoActivities<TItem>(IList<TItem> filterObject, Action<TItem> activity)
{
foreach (TItem item in filterObject)
{
activity(item);
}
}
Then you could pass a delegate/lambda expression:
List<SomeClass> items = new List<SomeClass>();
// ...
DoActivities(items, (item) => item.SomeClassMethod(/* ... */));
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.