Equivalent of Powershell [ValidateSet]

本文关键字:ValidateSet Powershell of Equivalent | 更新日期: 2023-09-27 17:50:56

在Powershell中,当我定义一个函数时,我可以很容易地使用[ValidateSet]指定参数的可能值列表,例如

function Log {
    param (
        [ValidateSet("File", "Database")] 
        [string]$Type = "File"
    )
    # my code
}

这样,我定义了一个默认值file和一组可能的值filedatabase。在c#中是否有类似的方法,或者我应该在构造函数中"手动"执行检查?

public Log(string type = "file") {
    public Log() {
        if ... # here goes my check on the string
    }
}

Equivalent of Powershell [ValidateSet]

如果只有有限范围的值,则可以使用枚举。首先设置枚举:

public enum MyValues
{
    File,
    Database
}

然后像使用其他参数类型一样使用

public void Log(MyValues type = MyValues.File)
{
    switch (type)
    {
        case MyValues.File:
            //Do file stuff here
            break;
        case MyValues.Database:
            //Do database stuff here
            break;
        default:
            throw new ArgumentException("You passed in a dodgy value!");
    }
}