通常,我试图创建一个PSCmdlet
,该参数需要实现IDisposeable
的类型的参数,并且需要处理以避免资源泄漏。我还想接受该参数的string
并创建该类型的实例,但是如果我自己创建该对象,那么我需要在从ProcessRecord
返回之前处理它。从其参数传递属性传递数据到PSCmdlet
为了从字符串建立我IDisposeable
对象我使用的是我的参数的ArgumentTransformationAttribute
,但我找不到任何方式从该类数据传递给我的PSCmdlet
我是否创建该对象与否。例如:
[Cmdlet("Get", "MyDisposeableName")]
public class GetMyDisposeableNameCommand : PSCmdlet
{
[Parameter(Mandatory = true, Position = 0), MyDisposeableTransformation]
public MyDisposeable MyDisposeable
{
get;
set;
}
protected override void ProcessRecord()
{
try
{
WriteObject(MyDisposeable.Name);
}
finally
{
/* Should only dispose MyDisposeable if we created it... */
MyDisposeable.Dispose();
}
}
}
class MyDisposeableTransformationAttribute : ArgumentTransformationAttribute
{
public override Object Transform(EngineIntrinsics engineIntrinsics, Object input)
{
if (input is PSObject && ((PSObject)input).BaseObject is MyDisposeable)
{
/* We were passed a MyDisposeable, we should not dispose it */
return ((PSObject)input).BaseObject;
}
/* We created a MyDisposeable, we *should* dispose it */
return new MyDisposeable(input.ToString());
}
}
我最好的猜测这里是继承我的MyDisposeableClass
只是标签,它需要明确的处置,但似乎相当哈克,而它的工作原理在这种情况下,它显然不会,如果我的工作想要处理一个密封的课程。
有没有更好的方法来做到这一点?
不幸的是,在这种情况下,“MyDisposeable”来自一个我无法修改的库,缺少一些反思。 – 2012-02-18 21:42:20