c# - 了解枚举

标签 c# enums

我试图弄清楚枚举是如何工作的,我试图创建一个写入注册表的函数,使用枚举作为注册表的根,但有点困惑

public enum RegistryLocation
        {
            ClassesRoot = Registry.ClassesRoot,
            CurrentUser = Registry.CurrentUser,
            LocalMachine = Registry.LocalMachine,
            Users = Registry.Users,
            CurrentConfig = Registry.CurrentConfig
        }

public void RegistryWrite(RegistryLocation location, string path, string keyname, string value)
{
     // Here I want to do something like this, so it uses the value from the enum
     RegistryKey key;
     key = location.CreateSubKey(path);
     // so that it basically sets Registry.CurrentConfig for example, or am i doing it wrong
     ..
}

最佳答案

问题在于您尝试使用类初始化枚举值并将枚举值用作类,但您无法这样做。来自 MSDN :

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

您可以做的是将枚举作为标准枚举,然后让一个方法根据该枚举返回正确的RegistryKey。

例如:

    public enum RegistryLocation
    {
        ClassesRoot,
        CurrentUser,
        LocalMachine,
        Users,
        CurrentConfig
    }

    public RegistryKey GetRegistryLocation(RegistryLocation location)
    {
        switch (location)
        {
            case RegistryLocation.ClassesRoot:
                return Registry.ClassesRoot;

            case RegistryLocation.CurrentUser:
                return Registry.CurrentUser;

            case RegistryLocation.LocalMachine:
                return Registry.LocalMachine;

            case RegistryLocation.Users:
                return Registry.Users;

            case RegistryLocation.CurrentConfig:
                return Registry.CurrentConfig;

            default:
                return null;

        }
    }

    public void RegistryWrite(RegistryLocation location, string path, string keyname, string value) {
         RegistryKey key;
         key = GetRegistryLocation(location).CreateSubKey(path);
    }

关于c# - 了解枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11805630/

相关文章:

c# - .NET DateTime 对象不是很准确?

c# - 在 WCF 的代码中将 IncludeExceptionDetailInFaults 设置为 true

c++ - C++中的枚举类型帮助

java - 使用 java reflect 找出两个类是否属于同一类型(类、接口(interface)、枚举等)

java - 设计枚举通用行为

c# - 在 LINQ 中,如何为每个 ID 选择一项?

c# - 基于偏好百分比的 Sitecore 多变量测试

swift - 我如何比较哪个嵌套枚举关联了我的值

java - 是否可以让 EMF Ecore 模型中的枚举实现接口(interface)?

c# - 使用 XmlSerializer 序列化 IntPtr