我有一个如下定义的枚举类型:
public enum Status
{
Active=1,
InActive=0
}
Run Code Online (Sandbox Code Playgroud)
在我的方法中,我可以将参数转换为枚举,如下所示:
public string doSomething(string param1, int status)
{
//will this work?
Account.Status = (Status) status;
//or do i need to test one by one like this
if(status == 0)
{
Account.Status = Status.Inactive;
//and so on...
} // end if
} // end doSomething
Run Code Online (Sandbox Code Playgroud)
只需检查 int 是否是 Status 的有效值,然后进行转换。
public string doSomething(string param1, int status)
{
if (IsValidEnum<Status>(status))
{
Account.Status = (Status)status;
}
...
}
private bool IsValidEnum<T>(int value)
{
var validValues = Enum.GetValues(typeof(T));
var validIntValues = validValues.Cast<int>();
return validIntValues.Any(v => v == value);
}
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以在 if 的 else 中抛出异常。
| 归档时间: |
|
| 查看次数: |
315 次 |
| 最近记录: |