Paulustrious wrote:
Thank you Andreas. You have added to the indentations in the wall. I tried
this...
class Program
{
static void Main(string [] args)
{
SomeProcess<SomeItem> ss = new SomeProcess<SomeItem>();
}
}
class SomeItem { }
class SomeProcess<T>
{
public List <SomeProcess<T>> Children = new List<SomeProcess<T>>() ;
void AddChild(SomeProcess<T> t) { Children.Add( t ); }
public void SomeSpecialMethod<U>(U u) where U :
SomeProcess<SomeItem> , T
{
Children.Add( (SomeProcess < SomeItem >) u );
}
}
But of course the Children.Add is causing the same old casting error. I can
see ways round it but only by being 'dirty'. (eg adding non-generalized
variables to my
SomeProcess class that are specially for <U> stuff. I am new to C# so my
answer to your question...
The AddChild(SomeProcess<T> t) signature is killing my solution :-(.
Thought it was AddChild(T t).
I then see no way to do that using pure generics, as they don't have
template specialization.
However switching behavior for special circumstances can be achieved in
a "classic" way using the strategy pattern and a factory. Here is a
little sketch of what I mean:
class SomeItem { }
interface SomeSpecialMethodExec<T>
{
void SomeSpecialMethod(SomeProcess<T> item);
}
class SomeSpecialMethodExecSomeItem : SomeSpecialMethodExec<SomeItem>
{
private List<SomeProcess<SomeItem>> l;
internal SomeSpecialMethodExecSomeItem(List<SomeProcess<Som eItem>> l)
{
this.l = l;
}
void
SomeSpecialMethodExec<SomeItem>.SomeSpecialMethod( SomeProcess<SomeItem>
item)
{// special for SomeItem.
l.Add(item);
}
}
class SomeSpecialMethodExecDefault<T> : SomeSpecialMethodExec<T>
{
private List<SomeProcess<T>> l;
internal SomeSpecialMethodExecDefault(List<SomeProcess<T>> l)
{
this.l = l;
}
void SomeSpecialMethodExec<T>.SomeSpecialMethod(SomePro cess<T> item)
{// normal execution
l.Add(item);
}
}
static class SomeSpecialMethodExecFactory
{
public static SomeSpecialMethodExec<T> Create<T>
(List<SomeProcess<T>> l)
{
if(typeof(SomeItem) == typeof(T))
return (SomeSpecialMethodExec<T>)new
SomeSpecialMethodExecSomeItem((List<SomeProcess<So meItem>>)(object)l);
return new SomeSpecialMethodExecDefault<T>(l);
}
}
class SomeProcess<T>
{
private List<SomeProcess<T>> Children = new List<SomeProcess<T>>();
private void AddChild(SomeProcess<T> t) { Children.Add(t); }
public void SomeSpecialMethod(SomeProcess<T> t)
{
// get method
SomeSpecialMethodExec<T> meth =
SomeSpecialMethodExecFactory.Create<T>(Children);
meth.SomeSpecialMethod(t);
}
}
BTW, It is usually more fun to get headache from a couple of beers that
from reorganizing some bricks ;-)
HTH,
Andy
--
To email me directly, please remove the *NO*SPAM* parts below:
*NO*SPAM*xmen40@*NO*SPAM*gmx.net