Can you write a c# decorator function that can take any number of arguments?
I currently have code which acts much like a python decorator, it takes a
function as argument and returns the same function wrapped by another (in
this case opening and closing a perforce connection).
public Func<TArg, TReturn> EnableP4<TReturn, TArgs>(Func<TArg,
TReturn> function)
{
Func<TArg, TReturn> p4Wrapper = (TArg funcArg) =>
{
try
{
if (con.Status.Equals(ConnectionStatus.Disconnected)) {
con.Connect(options); }
return function(funcArg);
}
finally { con.Disconnect(); }
};
return p4Wrapper;
}
At the moment this only works for functions with one argument and I was
wondering if it could be made more general (maybe if there is a way of
unpacking an array into a method?).
(Something along the lines of this?)
public Func<TArgs, TReturn> EnableP4<TReturn, TArgs>(Func<TArgs,
TReturn> function)
{
Func<TArgs, TReturn> p4Wrapper = (TArgs args) =>
{
try
{
if (con.Status.Equals(ConnectionStatus.Disconnected)) {
con.Connect(options); }
return function(*args);
}
finally { con.Disconnect(); }
};
return p4Wrapper;
}
where TArgs is a TArg[].
No comments:
Post a Comment