Sure.... 1) Write reusable code to that takes only objects of SomeType
that
also implements IDisposable. The code should call Dispose on all
contained
objects when you call Dispose on the container. The container shall only
contain objects of SomeType.
// generic collection
public class JALGenericCollection<T,R,P> : Disposable, IInvoke<R,P>
where T : IDisposable, IInvoke<R,P>
{
private readonly object syncLock = new object();
private List<T> list = new List<T>();
private R r = default(R);
public JALGenericCollection(R r)
{
this.r = r;
}
// ASSERT d is not null
// ASSERT no object holds a reference to
// d outside of this class
// USAGE Add(new MyClass()); ** newed reference idiom **
// where MyClass implements IDisposable and IInvoke
public void Add(T d)
{
if (d != null)
{
lock (syncLock)
{
if (disposed) { throw
new
ObjectDisposedException("JALGenericCollection"); }
list.Add(d);
}
}
else { throw new ArgumentException(); }
}
public void Clear()
{
lock (syncLock)
{
if (disposed) { throw
new ObjectDisposedException("JALGenericCollection");
}
foreach (IDisposable d in list)
{
d.Dispose();
}
list.Clear();
}
}
public R Invoke(P p)
{
R r = default(R);
// no one can add or delete during this critical section
lock (syncLock)
{
if (disposed) { throw
new ObjectDisposedException("JALGenericCollection");
}
foreach (IInvoke<R,P> i in list)
{
r= i.Invoke(p);
//if (this.r == r) break; // == on generic types NOT
ALLOWED!
}
}
return r;
}
protected override void DisposeManagedResources()
{
lock (syncLock)
{
foreach (IDisposable d in list)
{
d.Dispose();
}
}
}
protected override void DisposeUnmanagedResources()
{
// do nothing
}
}
2) Write code that simulates multiple inheritance of implementation so
that
you can plug in any set of concrete classes into the code that
implements the
set of interfaces of the class.
// finally we write the generic class that contains
// the concrete classes
public class GenericMI<T1, T2> : IProgram where T1 : class, I1,
new()
where T2: class,I2, new()
{
private T1 pimplI1= new T1();
private T2 pimplI2 = new T2();
// we forward calls to the contained object
public void SayHello()
{
pimplI1.SayHello();
}
public int GetValue()
{
return pimplI2.GetValue();
}
}
Regards,
Jeff
Are generics ANY useful for anything but to avoid boxing??<
*** Sent via Developersdex
http://www.developersdex.com ***