简体   繁体   English

无法将受保护的枚举作为静态方法的参数传递

[英]Can't pass protected enum as parameter for static method

I've been updating the company's software and stumbled upon this problem. 我一直在更新公司的软件,却偶然发现了这个问题。 There's this enum that's protected and I want to pass a value from that enum as a parameter for a static method, but I can't cause I have no access to it even though both the method and the enum are in the same class. 有一个受保护的枚举,我想从该枚举中传递一个值作为静态方法的参数,但是即使方法和枚举都在同一个类中,也无法使我无法访问它。

Example: 例:

Class SomeClass
{    
    protected enum Car
    {
        Id
    };

    public static void AMethod(Car enumValue)
    {
        MessageBox.Show("This is an enum:" + enumValue.ToString());
    }  
}

I can't use this Car enumValue as parameter for AMethod cause I have no access to it. 我不能用这个Car enumValue作为参数AMethod ,因为我有没有打开。 Why can't I do this? 我为什么不能这样做? I mean they're in the same class. 我是说他们在同一个班上。 Am I missing something? 我想念什么吗?

The issue is not that your SomeClass can't see the enum. 问题不是您的SomeClass看不到枚举。 The problem is your enum has a protected access modifier, and you're trying to use it in a public method (ie accessible outside your class). 问题在于您的枚举具有protected访问修饰符,并且您试图在public方法中使用它(即,可以外部访问)。 You can't expose a protected type through a public member because methods in other classes can't see the enum when they're trying to call AMMethod() . 您无法通过public成员公开protected类型,因为其他类中的方法在尝试调用AMMethod()时看不到枚举。

Depending on how you intend to use this class, you need to change either one or the other so the access modifiers match: 根据您打算使用此类的方式,您需要更改一个或另一个,以便访问修饰符匹配:

public enum Car
{
    Id
};

public static void AMethod(Car enumValue)
{
    MessageBox.Show("This is an enum:" + enumValue.ToString());
}  

or: 要么:

protected enum Car
{
    Id
};

protected static void AMethod(Car enumValue)
{
    MessageBox.Show("This is an enum:" + enumValue.ToString());
}  

The latter one will just prevent the compiler error, but it may be the case that you want AMethod to be public, so you should choose the former. 后者只会防止编译器错误,但是在某些情况下,您希望 AMethod是公共的,因此您应该选择前者。

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

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