gpt4 book ai didi

c# - 等效于 Powershell [ValidateSet]

转载 作者:行者123 更新时间:2023-11-30 12:25:52 24 4
gpt4 key购买 nike

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

最佳答案

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

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!");
}
}

关于c# - 等效于 Powershell [ValidateSet],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30486942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com