简体   繁体   English

如何访问在单独的类中声明的ENUM - C#

[英]How to access ENUM which is declared in a separate class - C#

I have the following code: 我有以下代码:

class EmployeeFactory
{
        public enum EmployeeType
        {
                ManagerType,
                ProgrammerType,
                DBAType
        }
}

I want to access this in MAIN class (Program). 我想在MAIN类(Program)中访问它。 I have written the following code. 我写了以下代码。 IT WORKS. 有用。 But I want to know how I can access the ENUM without instantiating the class -- Means ENUM is like a static variable (Class Level Variable) ? 但我想知道如何在不实例化类的情况下访问ENUM - 手段ENUM就像一个静态变量(类级变量)? Any help ? 有帮助吗?

class Program
{
        static void Main(string[] args)
        {
                Console.WriteLine(EmployeeFactory.EmployeeType.ProgrammerType);  // WORKS WELL
        }
}

or do I need to write it this way? 或者我需要这样写吗?

EmployeeFactory ef = new EmployeeFactory();
ef.EmployeeType.ProgrammerType

You can access it simply using the class. 您只需使用该类即可访问它。

EmployeeFactory.EmployeeType.ProgrammerType

The enum is part of the class, not part of a class instance. 枚举是类的一部分,不是类实例的一部分。

But I want to know how I can access the ENUM without instantiating the class 但我想知道如何在不实例化类的情况下访问ENUM

The original way you're accessing this enum 您访问此枚举的原始方式

Console.WriteLine(EmployeeFactory.EmployeeType.ProgrammerType);

already accomplishes that; 已经完成了; you are accessing the enum without instantiating the class. 正在访问枚举而不实例化该类。

try something like this ... 尝试这样的事......

    public interface IEnums
    {
        public enum Mode { New, Selected };
    }

    public class MyClass1
    {
        public IEnums.Mode ModeProperty { get; set; }
    }

    public class MyClass2
    {
        public MyClass2()
        {
            var myClass1 = new MyClass1();

            //this will work
            myClass1.ModeProperty = IEnums.Mode.New;
        }
    }

or you can directly access like this.... 或者你可以像这样直接访问....

 EmployeeFactory.EmployeeType.ProgrammerType 

i hope it will helps you 我希望它会对你有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM