How to get around the fact C# doesn't allow void as a generic parameter?
I have the following generic classes, which handle requests that return different kinds of objects:
class Request<T> {
/* ... */
public T Result { get; protected set; }
public abstract bool Execute();
protected bool ExecuteCore(params /* ... */) { /* ... */ }
}
class ObjectRequest<T> : Request<T>
where T : class, new() { /* ... */ }
class ListRequest<T> : R开发者_开发问答equest<List<T>>
where T : class, new() { /* ... */ }
class CompoundRequest<T, U> : Request<T>
where T : class, IHeader<U>, new()
where U : class, new() { /* ... */ }
class CompoundRequest<T, U, V> : Request<T>
where T : class, IHeader<U>, IHeader<V>, IHeader<W>, new()
where U : class, new()
where V : class, new() { /* ... */ }
class CompoundRequest<T, U, V, W> : Request<T>
where T : class, IHeader<U>, IHeader<V>, new()
where U : class, new()
where V : class, new()
where W : class, new() { /* ... */ }
interface IHeader<T> {
List<T> Details { get; set; }
}
Now I would like to create a class that handles requests that return no objects. However, setting a generic parameter to null is not allowed:
class NoReturnRequest : Request<void> { /* ... */ } // illegal
How do I get around this?
I'd recommend flipping your design pattern around; first you should build a non-generic Request
class that doesn't return anything, and from it inherit generic Request<T>
, Request<T1, T2>
, Request<T1, T2, T3>
, etc.. classes that do return values.
This is a common problem as languages such as C# become more functionally-oriented.
The Rx team solved it by introducing Unit.
Generics are used for a typed parameters. If the parameter does not have type, use interface or abstract from another class (which your Request will also inherit from)
精彩评论