为什么不允许nameof(object)?
问题描述:
在C#6.0中,您可以编写以下代码:
In C# 6.0 you can write this:
var instance = default(object);
var type = typeof(object);
它们具有以下相同的结果:
They have the same result of:
var instance = default(System.Object);
var type = typeof(System.Object);
但是你不能这样写:
var name = nameof(object);
它会产生以下错误:
无效的表达式术语对象".
Invalid expression term 'object'.
但是您仍然可以这样写:
But you can still write this:
var name = nameof(System.Object);
为什么nameof(object)
无法编译?
答
区别在于object
是类Object
的同义词,而nameof()
不适用于同义词.
The difference is that object
is a synonym for the class Object
and nameof()
doesn't work on synonyms.
对于nameof(int)
与nameof(Int32)