在左侧使用带有默认值(T)的 "is" 运算符
Using "is" operator with a default(T) on the left side
我有一个抽象 class 调用 AEntity,这是我游戏中实体的基础 class。
我还有一些接口可以连接到 "mark" 实体,例如:
interface EffectEntity<T> where T : AEntity
{
void UpdateEffect();
}
在我的程序的一部分中,我有一个 List<AEntity>
和一个名为 add 的方法。
此列表不能包含 EffectEntity
。这是我的添加方法代码:
if (Item is EffectEntity<T>)
{
throw new Exception("Cannot add an effectEntity to the still entities");
}
else allStillEntities.Add(Item);
这不会引发任何错误,但是当我将行 if(Item is EffectEntiy<T>)
更改为 if(default(T) is EffectEntity<T>)
时,它会发出警告 CS0148:"The given expression is never of the provided type ('EffectEntity<T>')
type"
这是为什么?他们不应该产生相同的结果吗?
是的,在左侧使用 Item
的版本可能更有效,但我仍然很好奇。
default(T)
将成为 null
,编译器知道这一点。 null
isn't an instance of EffectEntity<T>
,所以它知道它将是 false
。
Item
可能是也可能不是 null
、EffectEntity<T>
实例或其他类型的对象。
我有一个抽象 class 调用 AEntity,这是我游戏中实体的基础 class。
我还有一些接口可以连接到 "mark" 实体,例如:
interface EffectEntity<T> where T : AEntity
{
void UpdateEffect();
}
在我的程序的一部分中,我有一个 List<AEntity>
和一个名为 add 的方法。
此列表不能包含 EffectEntity
。这是我的添加方法代码:
if (Item is EffectEntity<T>)
{
throw new Exception("Cannot add an effectEntity to the still entities");
}
else allStillEntities.Add(Item);
这不会引发任何错误,但是当我将行 if(Item is EffectEntiy<T>)
更改为 if(default(T) is EffectEntity<T>)
时,它会发出警告 CS0148:"The given expression is never of the provided type ('EffectEntity<T>')
type"
这是为什么?他们不应该产生相同的结果吗?
是的,在左侧使用 Item
的版本可能更有效,但我仍然很好奇。
default(T)
将成为 null
,编译器知道这一点。 null
isn't an instance of EffectEntity<T>
,所以它知道它将是 false
。
Item
可能是也可能不是 null
、EffectEntity<T>
实例或其他类型的对象。