如何将class A
和class B
合并为例如单个通用类
public interface IA { }
public interface IB { }
public class A : IA, IDisposable
{
public void Clear()
{
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
//logic
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
public class B : IB, IDisposable
{
public void Detach()
{
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
//logic
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
public class BClearIfFail : B
{
private readonly Func<bool> _isFailed;
public BClearIfFail(Func<bool> isFailed)
{
_isFailed = isFailed;
}
protected override void Dispose(bool dispose)
{
if (dispose)
{
if (_isFailed())
{
Detach();
return;
}
}
base.Dispose(dispose);
}
}
public class AClearIfFail : A
{
private readonly Func<bool> _isFailed;
public AClearIfFail(Func<bool> isFailed)
{
_isFailed = isFailed;
}
protected override void Dispose(bool dispose)
{
if (dispose)
{
if (_isFailed())
{
Clear();
return;
}
}
base.Dispose(dispose);
}
}
换句话说,我需要这样的东西:
//not for compile =)
public class Single<T> : T where T : IDisposable
{
private readonly Func<bool> _whenSkip;
private readonly Action _howToSkip;
public Single(Func<bool> whenSkip, Action howToSkip)
{
_whenSkip = whenSkip;
_howToSkip = howToSkip;
}
public void Dispose()
{
if (_whenSkip())
{
Log.Message1(Resources.LogCleanupOfResourcesWillBeSkipped);
_howToSkip();
return;
}
T.Dispose();
}
}
我想如何在我的代码中使用此类:
public static class MyFactory<T>
{
public static T Create(bool skipCleanUp, Func<bool> isFailed, Action howToSkip)
{
return skipCleanUp ? new Single<T>(isFailed, howToSkip) : new T();
}
}
我尝试解释上下文:
public interface IUndoStack
{
void Push(Action action);
}
public class UndoStack : IUndoStack, IDisposable
{
private readonly Stack<Action> _undo = new Stack<Action>();
public UndoStack()
{
}
public void Push(Action action)
{
_undo.Push(action);
}
public void Clear()
{
_undo.Clear();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
foreach (var action in _undo)
{
try
{
action.Call();
}
catch (Exception e)
{
Log.Exception(e);
}
}
_undo.Clear();
}
}
}
//context
private void RestoreDatabase()
{
UndoStack undoStack = null;
try
{
undoStack = new UndoStack();
undoStack.Add(DeleteFiles())
CopyFiles(undoStack);
undoStack.Clear();
}
catch when(SkipCleanUpIfFail)
{
//Log
undoStack?.Clear();
throw;
}
finally
{
undoStack?.Dispose();
}
}