Skip to main content

Technique: Comment faire un cast dynamique en C# ?

En tant que langage fortement typé, C# sauve souvent la vie du développeur grâce à ses vérifications à la compilation. Il nous oblige à connaître lors de la compilation le type vers lequel on veut caster une variable, et c'est l'une de ses forces.

Pourtant, je suis tombé sur un cas où j'avais besoin d'un cast (transtypage) dynamique. J'ai en effet besoin d'appeler une méthode par réflexion, et le paramètre à lui passer doit être casté.

Considérons l'extrait de code suivant:

MethodInfo mi = adapterType.GetMethod("Update", parameterTypes);
object[] dataSetParameter = { ds };
mi.Invoke(UnderLyingAdapter, dataSetParameter);


Il sert à appeler la méthode Update d'un TableAdapter (celle-ci étant auto-générée, je n'ai pas d'autre choix que la réflexion pour l'appeler, mais c'est un autre sujet).

Eh bien, que se passe-t-il si la méthode Update attend un DataSet typé (auto-généré) alors que je n'ai qu'un simple DataSet (System.Data.DataSet) à lui passer? L'appel génère une exception, et à juste raison.

Tout cela est bel et bon, mais il m'est impossible d'écrire, avant l'appel à Invoke, une ligne du type:
object[] dataSetParameter = { (TypedDataSet) ds };
Car, justement, le type TypedDataSet n'existe pas à la compilation puisqu'il est auto-généré.

Après recherche, la seule possibilité de cast dynamique est offerte par la classe Convert, mais uniquement pour les types IConvertible, c'est à dire les types simples de .net (int, double et autres). J'ai fini par contourner le problème de manière à éviter le cast dynamique, mais je suis intéressé par d'autres retours d'expérience à ce sujet.

Comments

Anonymous said…
Thanks a lot for what You are doing!Information, that I managed to find here
is extremely useful and essential for me!With the best regards!
David
Anonymous said…
Great resource. keep it up!!Thanks a lot for interesting discussion, I found a lot of useful information!With the best regards!
Jimmy
Anonymous said…
Great job done, keep it up!with the best regards!

Popular posts from this blog

Learn Meteor book available

I'm pleased to announce the general release of my Learn Meteor book. It is now available as an ebook or print book from various sources: Learn Meteor print (paperback) on Lulu Learn Meteor ebook on LeanPub Learn Meteor ebook on Barnes & Noble Learn Meteor ebook on iBooks Learn Meteor ebook on Kobo Learn Meteor ebook on Scribd Learn Meteor ebook on Inktera Page Foundry Learn Meteor ebook on 24symbols Learn Meteor ebook on Amazon US Learn Meteor ebook on Amazon UK Learn Meteor ebook on Amazon France Learn Meteor ebook on Amazon Deutschland Learn Meteor ebook on Amazon Canada Learn Meteor ebook on Amazon India Learn Meteor ebook on Amazon Brasil Learn Meteor ebook on Amazon Mexico Learn Meteor ebook on Amazon España Learn Meteor ebook on Amazon Italia Learn Meteor ebook on Amazon Netherlands Learn Meteor ebook on Amazon Japan Learn Meteor ebook on Amazon Australia More sources are coming soon for the print version. Learn Meteor has been a fun experienc

Learn ASP.NET Core MVC book: published

As promised, the Learn ASP.NET Core MVC - Be ready next week using Visual Studio 2017  book is out today. You know nothing to ASP.NET Core but need to start coding your next application within a week. Don't worry: this book has you covered. Get your copy now: ebook on Leanpub , Amazon  (also in your local Amazon store), Kobo , Barnes&Noble Nook , Google Play , iBooks , 24symbols , Inktera , Scribd, Playster , Tolino, OverDrive, Bibliotheca Paperback on Lulu (soon available with other retailers) More about the book: You're a developer who knows nothing about ASP.NET Core MVC. Which is fine, except that you need to start coding your next application using ASP.NET Core 1.1 MVC and Visual Studio 2017.  Don't worry: I have you covered. I've been training hundreds of developers like you during 15 years, and converted my experience into this book. I know from experience teaching what takes more time to learn in ASP.NET Core MVC, and will spend time only