jeudi 26 avril 2018

Correct way to inferring parameter property with dynamic to generalize function?

I have a dozen different functions that takes a different objects each and do some work with the parameter object's id

public void MyFunctionForTypeA(TypeA value)
{
   DoSomething(value.Id);
}

public void MyFunctionForTypeB(TypeB value)
{
   DoSomething(value.Id);
}
...

assuming that every objects has an Id property, is there a way to generalize the functions?

I tried this, but I think/hope there's a better way

public void MyFunctionForEveryType(object value)
{
   dynamic myValue = value;
   DoSomething(myValue.Id);
}

(do I realy have to use dynamics in the first place? is there any reflection trick to achieve this?)

and no, sadly all parameters objects don't have a common interface or a base class of any kind :(





Aucun commentaire:

Enregistrer un commentaire