我怎么能对文字字符串参数设置约束

Mik*_*yev 4 c# constraints parameter-passing

我不得不说标题太差了,无法描述问题,但这是我唯一能想到的.无论如何,假设我得到了以下枚举:

public enum DocumentType{
      IdCard=0,
      Passport,
      DriversLicense
}
Run Code Online (Sandbox Code Playgroud)

我有一个方法接受一个字符串并返回上面的枚举:

public DocumentType GetDocTypeByString(string docType){
    switch (docType)
    {
       case "ID":
         return DocumentType.IdCard;
       case "PASS"
         return DocumentType.Passport;
       //and so on
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果传递的字符串不符合任何切换条件怎么办?最愚蠢的事情是制作返回类型对象,但这是某些人几乎不会做的事情.如果enum是我的,我会添加一个名为"None"的附加值,并在没有匹配的情况下返回,但我无法控制它.然后我想,是否可以将输入约束到某些值.就C#而言,我几乎完全相信它是不可能的,但无论如何我决定问.在这种情况下你会推荐吗?

xan*_*tos 5

不,你不能.通常使用的模式是抛出一个

throw new ArgumentException("docType");
Run Code Online (Sandbox Code Playgroud)

技术上甚至是一个

throw new ArgumentOutOfRangeException("docType");
Run Code Online (Sandbox Code Playgroud)

这是正确的,但我从未见过它在"数字"索引之外使用.

例如,如果您使用非法值,则Enum.Parse抛出一个ArgumentException,并且您的方法似乎与此非常相似.

其他选择是使用Enum.TryParse模式:

public static bool TryGetDocTypeByString(string docType, out DocumentType documentType) 
{
    switch (docType)
    {
        case "ID":
            documentType = DocumentType.IdCard;
            return true;
        case "PASS"
            documentType = DocumentType.Passport;
            return true;
    }

    documentType = default(DocumentType);
    return false;
}
Run Code Online (Sandbox Code Playgroud)