c# - How can you explicitly cast a variable of type 'object' to satisfy a multi-typed generic constraint? -


we have generic extension method works objects supports both inotifycollectionchanged , ienumerable interfaces. it's written this:

public static class someextensions {     public static void dosomething<t>(this t item)     t : inotifycollectionchanged, ienumerable     {         //     } } 

the following compiles fine since observablecollection<string> implements both interfaces , 'var' keyword, knowntype typed:

var knowntype = new observablecollection<string>(); knowntype.dosomething(); 

however, trying call valueconverter. problem incoming value of type object , though can test passed-in object implement both interfaces, can't figure out how explicitly cast can call generic extension method. doesn't work (obviously)...

object unknowntype = new observablecollection<string>(); ((inotifycollectionchanged,ienumerable)unknowntype).dosomething(); 

so how can cast object multiple interfaces can call generic? not sure it's possible.

the cleanest way can think dynamic. however, because extension methods don't play nice dynamic (see blelow), you'll have reference extension method explicitly.

extensions.dosomething(unknowntype dynamic); 

edit warning aginst gotcha ran here, note calling method explicit dyanmic type argument (via dosomething<dynamic>) not work - causes compile errors when trying match against multiple constraints. in addition, when not using multiple constraints, results in dynamic resolving based on passed variable's compile-time type, not runtime type.

this result in call extensions.unknowntype<dynamic>, dynamic of resolve @ runtime - meaning it'll use derived type of given parameter. long parameter implements desired interfaces, off go.

be wary as, dynamic code, encounter issues won't seen until runtime. use sparingly!

if make multiple calls same generic paremeters, might better off adding generic helper method in converter , calling that using value dynamic

addendum:

when using dynamic, called against dynamic object attempt resolve member of given type @ runtime, not extension methods, since inherently exist in different class, different assembly.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -