【问题标题】:Creating a method that accepts both Vector2 and Vector3 arguments in C#在 C# 中创建一个同时接受 Vector2 和 Vector3 参数的方法
【发布时间】:2020-04-16 13:15:28
【问题描述】:

我从 C# 开始,在编写一个在 C# 中同时接受 Vector2 和 Vector3 参数的方法时遇到问题。

泛型方法看起来不错,但我现在还不能让它工作。这是我尝试过的:

static void GetNoisePosition<T>(ref T position, float offset, float scale) where T : IEquatable<T>
{
    position += position.GetType().one * (offset + 0.1f);
    position *= scale;
}

我真的不想拥有 2 个版本的 GetNoisePosition,每个版本都采用矢量类型,因为我不想复制逻辑,而且很难创建另一个可以共享其中一些逻辑的方法。

所以,问题是我想在类型 T 的类上调用 one 方法,但它告诉我不能。

我可以通过position 实例访问该类并调用它吗?

【问题讨论】:

  • position.GetType().GetProperty("one").GetValue(null)
  • “我真的不想拥有两个版本的 GetNoisePosition” - 为什么?如果它们有一些共同点,那么该共同点可能是基类或接口的一部分。否则,您将处理 2 种不同的类型并访问它们完全不同的属性。方法重载才是王道。
  • 或者,只使用Vector3 position,因为Vector2 可以隐式转换为Vector3
  • 没关系,我刚刚注意到这是一个ref 参数
  • position.GetType().GetProperty("one").GetValue(null) 本身很好,但是我不能在上面使用* 方法。

标签: c# overloading strong-typing generic-method


【解决方案1】:

获取向量的类型,以及使用反射的操作符方法:

public static void CalculateNoisePosition<T>(ref T position, float offset, float scale)
{
  Type vector = position.GetType();
  MethodInfo add = vector.GetMethod("op_Addition", new[] {typeof(T), typeof(T)});
  MethodInfo multiply = vector.GetMethod("op_Multiply", new[] {typeof(T), typeof(float)});

  T one = (T) vector.GetProperty("one").GetValue(null);

  position = (T) add.Invoke(null, new object[] {position, multiply.Invoke(null, new object[] {one, offset + 0.1f})});
  position = (T) multiply.Invoke(null, new object[] {position, scale});
}

请注意,如果您调用此方法时 T 不是 Vector2Vector3,您很可能会得到 NullReferenceException

与往常一样,当涉及到反射时,请分析代码并决定是否值得使用这种方法,而不是编写 2 个几乎相同的方法。

【讨论】:

  • 感谢您抽出宝贵时间。我绝对不会用它来代替 2 个简单的方法,但我可能会从中学到一些东西。
  • 最后一个问题很快:假设我有一个简单的声明static void GetNoisePosition&lt;T&gt;(ref T position)。我不能简单地调用position 上的方法吗?即使我只是使用position.x,它也不起作用。
  • 不,因为你不知道T。您必须使用反射来获取所有属性。您也不能使用类型约束,因为Vector2Vector3 不共享公共接口,而且它们是结构,因此它们也没有公共基类。
  • 我的建议是从position 中删除ref 说明符,而是返回计算值。然后,键入 Vector3 而不是 T,因为 Vector2 可以隐式转换为 Vector3
  • 或者,如果您真的想要,您可以使用Vector2 进行另一个重载,使用Vector3 调用重载
猜你喜欢
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多