我觉得这是个有点傻的问题但是..。
我知道,这是规矩,但不知道,为什么。对于两个名为T1
& T2
的类型,我可以:
if (typeof(T1) == typeof(T2))
...
,但不能直接前进:
if (T1 == T2)
为什么?
发布于 2022-01-29 12:26:49
正如Joey所提到的,由于C#语言的语法,不能直接将类型名称(如T1
、T2
(或string
、int
等)用作表达式。请参考以下语法规范:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure
因此,表达式T1 == T2
是无效的(从编译器的角度来看)如下:
if (string == int) // <-- what does that even mean? Shouldn't that always be false?
Console.WriteLine("Hooray!");
由于类型名称没有任何附加的变量类型,所以必须使用typeof(...)
语法从运行时获取类型表示(实际上,该语法返回System.Type
类型的值)。
在允许T1 == T2
时可能遇到的另一个问题是:
struct t1 { }
void Main<T1, T2>()
{
Type t1 = typeof(T1); // so far, so good.
if (t1 == T2) // wait, I'm the compiler and I am confused right now.
// Is t1 a type or a variable of the type 'System.Type'?
Console.WriteLine("Hooray!");
}
编译器应该如何处理这个代码片段?添加或删除结构T1
将破坏Main
函数的行为,从而在重新编译时破坏二进制兼容性。
https://stackoverflow.com/questions/41759548
复制相似问题