建议 GetComponent<>() 进行变量赋值时如何推断类型?

问题描述

这就是我写的(很多):

Rigidbody rb = G

现在我希望 ReSharper Code Completion 向我建议:

GetComponent<Rigidbody>()

但事实并非如此。它建议 GetComponent<>() 并让我自己填写类型。我真正想要的是这样的:

SomeComponent foo = GetComponent<SomeComponent>();

ReSharper 应该拥有在即将分配变量时进行此类型推断所需的所有信息。

有没有办法手动将这种建议添加到 ReSharper,从而推断出正确的类型?我尝试过实时模板,但似乎没有办法访问我要分配的变量的类型。

解决方法

这很正常, 类似于 () 但不同,就像询问 ReSharper 为什么不填写参数一样,仅此而已。

,

我找到了解决方案here

您可以使用 macros 代替 Live Template variables 来推断 ReSharper 在变量点猜测的类型。

  1. 打开 Rider 设置 [Ctrl+Alt+S] 并导航到编辑器 > 实时模板 > C# 或 Unity(无论您喜欢作为新模板的位置)
  2. 使用您偏好的快捷方式(在我的情况下为 gc)和以下内容创建模板:GetComponent<$TYPE$>();$END$

enter image description here

  1. 点击 Availability 并添加 Unity C# fileC# 2.0+ expressions 的范围(这只是定义了 ReSharper 建议快捷方式的位置)
  2. 点击右下角的 Edit Variables
  3. TYPE的宏改成Guess type expected at this point

enter image description here

  1. 点击 Save 并使用如下模板:

enter image description here

感谢安德鲁提出这个解决方案。如果您希望在 Rider 中默认看到此功能,upvote it here