Enum on namespace level - still needs to be public?
I am not sure why the enum there must be public in order to be used with the delegate. I assumed when on namespace level, the whole app can access it, as it is in the scope.
namespace Test
{
enum Days
{
Monday,Tuesday
}
class TestingClass
{
public delegate void DelTest(Day开发者_Python百科s d) /// ERROR, type enum is less accessible
}
}
Your delegate type is actually declared within an internal
class, so it's effectively internal too (in some senses, anyway). That's why your example as shown will compile (after adding the semi-colon). To make it break, you'd have to make TestingClass
public too. So options:
- Leave it as shown
- Make the delegate explicitly internal, if you want TestingClass to be public
- Make the enum explicitly public, if you want everything to be public
Just to explain why your current code would be broken if TestClass
were public: the delegate would be public, and therefore visible outside the current assembly. That means all its parameters and the return type have to be visible too.
Don't forget that the default access level for a member in C# is always "the most restrictive access level that could be explicitly specified for that member" - so for a top-level type (including an enum), the default accessibility is internal
.
The accessibility of your enum must match the delegate. Think about how you're going to call it.
new TestingClass.DelTest(Days.Monday).Invoke();
To be able to do this from a different assembly, the Days enum must be public. If you don't want it to be public, change the accessibility of the delegate to match that of the enum, e.g. set both to be internal.
I assumed when on namespace level, the whole app can access it
No, the whole assembly can access it. The default access level is internal
.
Edit: When I change your code to use a public class:
enum Days { ... }
public class TestingClass { void M(Days d) {} }
I do get a compile error
Inconsistent accessibility: parameter type 'Test .Days' is less accessible than ...
And that is what @firefox explains: a parameter-type in a public
method must also be public
, to avoid inconsistencies. Currently your Days type is less accessible (internal
).
This piece of code compiles fine for me too, with the addition of the semi colon.
The error of "parameter type is less accessible than the delegate" would only occur if the class accessibility is raised, as currently they are defined with the same accessibility level, internal.
e.g.
namespace Test
{
enum Days
{
Monday, Tuesday
}
public class TestingClass
{
public delegate void DelTest(Days d); // This will produce an error...
}
}
精彩评论