in referencing enum type why do i need to add namespace and class in declaration of the enum?
namespace myobjects
{
开发者_如何学C class mylifeforms
{
public enum Animal { dog, cat, mouse }
}
}
if i want to use the the enum type in a class i need to declare the type like this:
myobjects.mylifeforms.Animal animal;
what should i do so i can declare it like:
Animal animal;
Put the enum in the namspace instead of in the class. Than you can add the namepace with using
to get what you want.
namespace myobjects
{
public enum Animal { dog, cat, mouse }
class mylifeforms
{
}
}
Now if you add
using myobjects;
in the file where you want to use your enum you will get what you want.
Within the mylifeforms
class you can reference the Animal
enum just by itself, but outside mylifeforms
you need to use mylifeforms.Animal
. It's specified in a roundabout way in sections 10.3.8.1 and 3.8 of the C# spec; the name resolution algorithm simply doesn't consider nested types when given a simple name.
You'll need to declare Animals
in the namespace rather than the class to refer to it using it's simple name everywhere
The reason for this is that you have placed the enum inside of the class.
if you defined the enum inside the namespace alone, it would not be needed.
So it would look like this.
namespace myobjects
{
class mylifeforms
{
}
public enum Animal { dog, cat, mouse }
}
Then you could use myobjects.Animal
to reference the enum. A simple using myobjects;
would then allow you to do it as Animal
.
You'll have to create a manual type alias in your using
statements at the start of the file.
using Animal = MyObjects.MyLifeForms.Animal;
This is because you declared the enum
within the class rather than at the namespace level. If you were to do this:
namespace MyObjects
{
public class MyLifeForms
{
...
}
public enum Animal
{
...
}
}
It would be accessible as Animal
to any file that uses the MyObjects
namespace.
Does it work if you declare the enum above the class , but within the namespace ?
You can use:
#define myobjects.mylifeforms.Animal Animal
精彩评论