通常,我正在尝试创建一个PSCmdlet
采用实现IDisposeable
并需要处置的类型的参数以避免泄漏资源的参数。我还想接受string
该参数的 a 并创建该类型的实例,但是如果我自己创建该对象,那么我需要在从ProcessRecord
.
我正在使用ArgumentTransformationAttribute
我的参数来从字符串构造我的IDisposeable
对象,但我找不到任何方法将数据从该类传递给我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
只是为了标记它需要显式处理,但这似乎相当hacky,虽然它在这种情况下有效,但如果我想处理一个密封的类,它显然是行不通的。
有一个更好的方法吗?