问题
bool
,int
,andstring
(to name a few), are all aliases of System
types.
They can all be used without the System
directive being included.
Yet the types they alias can't be used without the System
directive.
public class Test
{
public static void Main()
{
bool b; //valid
Boolean b2; //compiler error
int i; //valid
Int32 i2; //compiler error
string s; //valid
String s2; //compiler error
}
}
I have few questions as to why this works.
Is the compiler making an exception for these commonly used types?
Is the
System
directive being looked at to determine the aliasing, but not being looked at for the other types?Is it always safe to use
bool
,int
,string
, etc without theSystem
directive?
回答1:
Is the compiler making an exception for these commonly used types?
Yes.
Is the System directive being looked at to determine the aliasing, but not being looked at for the other types?
Yes. Well, sort of. There is no System directive. There is a using
directive, with which you can import the System
namespace, which defines the types.
Is it always safe to use bool, int,string, etc without the System directive?
Yes.
Many modern languages like C# are heavily inspired from C++, which is in turn heavily inspired from C. The C language had taken the innovative stance of complete separation between compiler and runtime. The compiler of C was (is) making absolutely no assumptions about the standard libraries. In theory, it is possible to write C programs that do not include the standard libraries.
However, languages like C# accept that there is significant merit in having a certain degree of collusion between the compiler and the runtime. Many C# keywords depend on support from the runtime. A very good example of that, the yield return
keyword. Other examples are the types that your question is asking about.
回答2:
If you refer to https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx you see that the built-in boolean type is an alias for System.Boolean
and not Boolean
that is the aliases are fully qualified.
So when you write int x;
it gets aliased to System.Int32 x;
and not just Int32
or else they might collide if you defined a type called Int32
in your own namespace.
Using these built in types should always be safe, you do not have same problem as C/C++ sometimes has where "built in" types have different underlying types and therefore return different values when sizeof
is called on them depending on platform.
来源:https://stackoverflow.com/questions/39901416/how-are-type-aliases-resolved-when-the-system-directive-is-missing