i have event class:
sealed class anevent : eventargs { ienumerable<itemwrapper<anabstractclass>> items { get; set; } }
which used this:
class itemsprocessor { delegate void onitemsprocessedhandler(object sender, anevent e); event onitemsprocessedhandler onitemsprocessed; //... }
i use wrapper class:
sealed class itemwrapper<t> t: anabstractclass { t item { get; set; } metadata metadata { get; set; } itemwrapper(t item, metadata metadata) { item = item; metadata = metadata; } }
and have method in itemsprocessor
class :
internal void dosomethingwithlist<t>(ienumerable<t> items) t: anabstractclass, new() { ienumerable<itemwrapper<t>> processeditems = wrapitems<t>(items); onitemsprocessed(this, new anevent() { items = processeditems }); //error here }
the issue on last line of code sample; when try set property items
of anevent
local ienumerable
. compiler refuses proceed telling me cannot implicitly cast ienumerable<itemwrapper<t>>
ienumerable<itemwrapper<anabstractclass>>
. thought should okay since added constraint where t: anabstractclass, new()
method when explicitly casting (using either classic casting parenthesis or using convert<>
) invalidcastexception
.
my current workaround method dosomethingwithlist
:
var temp = processeditems.select(x => { return new itemwrapper<anabstractclass>(x.item, x.metadata); }); onitemsprocessed(this, new anevent() { items = temp });
so working fine wondering why couldn't work without using linq
conversion has iterate on items in list? seems obvious me should able cast without error since added constraint and explicit cast make compiler accepts code there exception raised... point me going wrong here?
abstract class anabstractclass { } class itemclass : anabstractclass { }
a wrapitems
quick implementation easy copy-pasting if want try:
ienumerable<itemwrapper<t>> wrapitems<t>(ienumerable<t> items) t : anabstractclass, new() { list<itemwrapper<t>> ret = new list<itemwrapper<t>>(); foreach (var item in items) { ret.add(new itemwrapper<t>(item, new metadata())); } return ret; }
if change itemwrapper
sealed class itemwrapper { anabstractclass item { get; set; } metadata metadata { get; set; } itemwrapper(anabstractclass item, metadata metadata) { item = item; metadata = metadata; } }
what have lost?
Comments
Post a Comment