有没有办法将类中的枚举属性设置为所有可用的枚举?

Eon*_*Eon 9 c# enums

首先,我不知道如何标题这个问题 - 我甚至对如何陈述它感到困惑.

现在提出问题.让我们把System.IO.FileSystemWatcher你设置它的NotifyFilter属性的类:

            this.FileSystemWatcher1.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName 
            | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security 
            | NotifyFilters.Size;
Run Code Online (Sandbox Code Playgroud)

这是设置单个属性的相当多的代码.检查NotifyFilter,这是一个列举.是否有" 懒惰 "或" 快捷 "方式一次性设置所有这些属性?我知道这不一定需要,但我的好奇心被激怒了.

this.FileSystemWatcher1.NotifyFilter = <NotifyFilters.All>

Mat*_*gen 13

你总是可以这样做,

NotifyFilter ret = 0;
foreach(NotifyFilter v in Enum.GetValues(typeof(NotifyFilter)))
{
    ret |= v;   
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我不知道更好的方法.但是你总是可以在通用的实用方法中抛出它.

private static T GetAll<T>() where T : struct, IConvertible
{
    if (!typeof(T).IsEnum)
    {
       throw new NotSupportedException(); // You'd want something better here, of course.
    }

    long ret = 0; // you could determine the type with reflection, but it might be easier just to use multiple methods, depending on how often you tend to use it.
    foreach(long v in Enum.GetValues(typeof(T)))
    {
        ret |= v;
    }

    return (T)ret;
}
Run Code Online (Sandbox Code Playgroud)

  • 只是一个FYI,你可以说`foreach(Enum.GetValues中的NotifyFilter(typeof(NotifyFilter)))`将演员保存在foreach体内. (2认同)

ajg*_*ajg 6

没有编写自己的方法是没有办法的 - 正如其他地方正确回答的那样.

如果枚举是你的改变,你可以添加一个新的值

All = ~0
Run Code Online (Sandbox Code Playgroud)