質問

I have a few ObservableCollections with different object models, all inheriting from the same base model. For example:

class Food { }
class Pizza : Food { }
class Rice : Food { }
class Spaghetti : Food { }

and an ObservableCollection for each one:

ObservableCollection<Pizza> pizzaOC;
ObservableCollection<Rice> riceOC;
ObservableCollection<Spaghetti> spOC;

Then I have a method which has an ObservableCollection<Food> parameter, like so:

private bool CheckFood(ObservableCollection<Food> foodItems)
{
    // stuff here
}

The problem comes when I try to do the calls :

CheckFood(pizzaOC);
CheckFood(riceOC);
//...

Is there any way I can call a single method, but passing different types of ObservableCollections? And also, is there a way to find out in the method, which OC type has been passed?

役に立ちましたか?

解決

private bool CheckFood<T>(ObservableCollection<T> foodItems) where T: Food
{
   ...
}

You can determine type of food passed to method with something like typeof(T) but it's better to move responsibility for logic to class itself

他のヒント

If your method does not rely on the argument being explicitly ObservableCollection<T>, you could always code to the interface:

public bool CheckFood<TCollection, TItem>(TCollection collection)
    where TCollection : ICollection<TItem>, INotifyCollectionChanged
    where TItem : Food
{
    // something
}

This means if you want to use a custom "Observable Collection" you don't need to rely on it inheriting from ObservableCollection.

Additionally to find out what type has been passed through to the method you can call the following within the method:

var type = typeof(TItem);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top