问题
I have recently begun experimenting with Binary PowerShell Programming in C#, and I am having some trouble with ParameterValidationAttributes, the ValidateScript Attribute mostly. Basically, i want to create a Param named "ComputerName" and validate the computer is online at that time. It was easy in PowerShell:
[Parameter(ValueFromPipeLine = $true)]
[ValidateScript({ if (Test-Connection -ComputerName $_ -Quiet -Count 1) { $true } else { throw "Unable to connect to $_." }})]
[String]
$ComputerName = $env:COMPUTERNAME,
But i cannot figure out how to replicate that in C#. the ValidateScript attribute takes a ScriptBlock object http://msdn.microsoft.com/en-us/library/system.management.automation.scriptblock(v=vs.85).aspx im just not sure how to create that in C#, and i cannot really find any examples.
[Parameter(ValueFromPipeline = true)]
[ValidateScript(//Code Here//)]
public string ComputerName { get; set; }
C# is very new to me, so i appologize if this is a dumb question. here is a link the ValidateScript Attribute Class: http://msdn.microsoft.com/en-us/library/system.management.automation.validatescriptattribute(v=vs.85).aspx
回答1:
It is not possible in C#, since .NET only allow compile time constants, typeof
expressions and array creation expressions for attribute parameters and only constant available for reference types other then string
is null
. Instead you should derive from ValidateArgumentsAttribute
and override Validate
to perform validation:
class ValidateCustomAttribute:ValidateArgumentsAttribute {
protected override void Validate(object arguments,EngineIntrinsics engineIntrinsics) {
//Custom validation code
}
}
回答2:
Just to expand on user4003407's answer above with a more complete example.
Derive a new validator from ValidateArgumentsAttribute and override Validate to perform validation. Validate is void so you really just get to throw exceptions in cases you choose.
Kevin Marquette has an excellent article but it's in powershell. Here is a c# example:
[Cmdlet(VerbsCommon.Get, "ExampleCommand")]
public class GetSolarLunarName : PSCmdlet
{
[Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)]
[ValidateDateTime()]
public DateTime UtcDateTime { get; set; }
protected override void ProcessRecord()
{
var ExampleOutput = //Your code
this.WriteObject(ExampleOutput);
base.EndProcessing();
}
}
class ValidateDateTime:ValidateArgumentsAttribute {
protected override void Validate(object arguments,EngineIntrinsics engineIntrinsics) {
var date = (DateTime)arguments;
if( date.Year < 1700 || date.Year > 2082){
throw new ArgumentOutOfRangeException();
}
}
来源:https://stackoverflow.com/questions/27908470/validatescript-parameterattribute-in-c-sharp-binary-powershell-module