我正在使用遗留代码,并将单实例实现转换为多个实例。
下面的基本示例说明了我在做什么 -
代码在这里:
// An Interface
public interface IImplementation
{
void DoSomething();
double MeasureSomething();
}
// An implementation
public class Implementation : IImplementation
{
private int iparam;
private string sparam;
public Implementation(string sparam, int iparam)
{
this.sparam = sparam;
this.iparam = iparam;
}
public void DoSomething()
{
//actually do something here
}
public double MeasureSomething()
{
double value = 0.0;
//actually measure something here
return value;
}
}
// a disposable safety wrap object
public class SafetyWrap : IDisposable
{
public SafetyWrap(string resource)
{
mutex = new Mutex(false, resource);
try
{
if (mutex.WaitOne(Timeout.Infinite) == false)
throw new TimeoutException("Timed out trying to acquire lock");
}
catch (AbandonedMutexException)
{
// Log "Caught abandoned mutex"
}
}
private Mutex mutex;
#region IDisposable Members
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
mutex.ReleaseMutex();
mutex.Close();
}
disposed = true;
}
}
~SafetyWrap()
{
Dispose(false);
}
#endregion IDisposable Members
}
// a wrapper class to protect the object
public class WrappedImplementation : IImplementation
{
private IImplementation objectToWrap;
private string mySafetyString;
public WrappedImplementation(IImplementation objectToWrap)
{
this.objectToWrap = objectToWrap;
mySafetyString = "GeneratedToPreventConflicts";
}
#region IImplmentation Members
public void DoSomething()
{
using (new SafetyWrap(mySafetyString))
{
objectToWrap.DoSomething();
}
}
public double MeasureSomething()
{
using (new SafetyWrap(mySafetyString))
{
return objectToWrap.MeasureSomething();
}
}
#endregion IImplmentation Members
}
internal class Program
{
private static void Main(string[] args)
{
IImplementation normalObject = new Implementation("dummy", 1);
IImplementation safeObject = new WrappedImplementation(normalObject);
}
}
然而,这涉及创建大量的样板(我实际上有许多接口要实现),但它仍然不能保证它们可以和/或将被用于他们可能/应该的任何地方。
是否有更好的替代方法来实现这一目标?
答案 0 :(得分:0)
您可以生成代码。
为此,我相信一个非常小的生成器代码将完成任务。您可以获取要为其生成包装器的接口成员,并通过设计时T4模板生成包装器的代码。这样,您可以避免重复的概念,并且只需更改生成代码的模板即可轻松更改所有实现。
这种方法的缺点是,智能感知支持和Visual Studio for T4模板内置的默认编辑器目前非常差(实际上很长一段时间,甚至)。
答案 1 :(得分:0)
我建议动态地发布(用System.Reflection.Emit
)实现来减少dll文件的大小,项目中的样板量和编译时间。