我希望每种基本类型都有2d矢量类。
现在,为了确保最佳的运行时性能并能够使用许多实用程序函数,我需要为每个基元(Vector2Int,Vector2Float,Vector2Long等)提供单独的类。
这只是很多复制粘贴,如果我必须做出改变,我必须记住在每个类和每个实用功能中都要做。
有没有什么可以让我写一些像C ++模板(或者有什么方法可以创建它)?
我创建了一个小概念来向您展示这将如何工作:
// compile is a keyword I just invented for compile-time generics/templates
class Vector2<T> compile T : int, float, double, long, string
{
public T X { get; set; }
public T Y { get; set; }
public T GetLength()
{
return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2));
}
}
// during compilation, code will be automatically generated
// as if someone manually replaced T with the types specified after "compile T : "
/*
VALID EXAMPLE (no compilation errors):
autogenerated class Vector2<int>
{
public int X { get; set; }
public int Y { get; set; }
public int GetLength()
{
return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2));
}
}
UNVALID EXAMPLE (build failed, compilation errors):
autogenerated class Vector2<string>
{
public string { get; set; } // ok
public string { get; set; } // ok
public string GetLength()
{
return Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2)); // error! string cannot be used with Math.Pow()
// and Math.Sqrt doesn't accept string type
}
}
*/
有没有一些聪明的方法来实现这一点,还是这完全不可能?
很抱歉不太清楚,但让我解释一下问题所在。
考虑使用普通的C#泛型。 GetLength()方法不会编译,因为我想要使用的所有类型(int,float,double,long)都需要共享Math.Pow()应该接受的接口作为参数。
字面上用类型名称替换“T”标记可以解决这个问题,提高灵活性,达到手写代码性能并加快开发速度。
我创建了自己的模板生成器,通过编写C#代码生成C#代码:) http://www.youtube.com/watch?v=Uz868MuVvTY