本文介绍了C#二进制PowerShell模块中的ValidateScript ParameterAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始尝试使用C#进行二进制PowerShell编程,并且在使用ParameterValidationAttributes(主要是ValidateScript属性)时遇到了一些麻烦.基本上,我想创建一个名为"ComputerName"的参数,并确认计算机当时处于联机状态.在PowerShell中很简单:

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,

但是我不知道如何在C#中复制它. ValidateScript属性采用ScriptBlock对象 http://msdn.microsoft.com/zh-CN/library/system.management.automation.scriptblock(v = vs.85).aspx 我只是不确定如何在C#中创建它,而我真的找不到任何例子.

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#对我来说很陌生,因此我很抱歉这是一个愚蠢的问题.这是ValidateScript属性类的链接: http://msdn.microsoft.com/zh-cn/library/system.management.automation.validatescriptattribute(v = vs.85).aspx

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

推荐答案

在C#中是不可能的,因为.NET仅允许对属性参数使用编译时常数,typeof表达式和数组创建表达式,并且仅常数可供参考stringnull以外的其他类型.相反,您应该从ValidateArgumentsAttribute派生并覆盖Validate以执行验证:

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
    }
}

这篇关于C#二进制PowerShell模块中的ValidateScript ParameterAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 00:22