如何改进C#enum

如何改进C#enum,c#,validation,enums,C#,Validation,Enums,如果我创建这样的枚举 public enum ImportType { Direct, Indirect, InBond } 我有一个方法,它将ImportType作为参数,如下所示 public bool ProcessValidImport(ImportType type) { // Process ImportType variable here } bool blnProcessed = ProcessValidImport((ImportType)7);

如果我创建这样的枚举

public enum ImportType
{
   Direct,
   Indirect,
   InBond
}
我有一个方法,它将ImportType作为参数,如下所示

public bool ProcessValidImport(ImportType type)
{
    // Process ImportType variable here
}
bool blnProcessed = ProcessValidImport((ImportType)7);
我可以按如下方式调用该方法

public bool ProcessValidImport(ImportType type)
{
    // Process ImportType variable here
}
bool blnProcessed = ProcessValidImport((ImportType)7);

但是传递给方法的
ImportType
变量值
7
是无效的,因为如果强制转换,任何整数都可以工作。枚举默认为int类型,那么在这种情况下,验证枚举是否为有效的
ImportType
的最佳方法是什么呢

我不知道我是否正确理解您的意思,但您可以使用以下方法轻松验证枚举:

int value = 7;
bool isDefined = Enum.IsDefined(typeof (ImportType), value);

您可以创建并抛出一个
ArgumentOutOfRangeException
。是否正在查找此ProcessValidImport(ImportType.Direct);?我只是不想用它们。。。。它们对于标记非常有用,例如
BindingFlags.Public | BindingFlags.Instance
,但在我看来,如果在控制流中使用它们,那么您几乎不会始终遵循“打开-关闭”。@Callumlington是否会使用下面类似“Enum.IsDefined”的验证来确保类的内部工作保持不变?从而维持开闭本金?对不起,我是新手,所以我真的不知道。我知道我可以通过继承扩展类来“打开”类。这正是我想要的答案。我对它进行了测试,它100%有效。非常感谢你!