我希望每种基本类型都有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 …Run Code Online (Sandbox Code Playgroud) 例:
我想要从TextBox或RichTextBox派生几个专门的文本框,它们都派生自TextBoxBase:
class CommonFeatures<T> : T where T : TextBoxBase
{
// lots of features common to the TextBox and RichTextBox cases, like
protected override void OnTextChanged(TextChangedEventArgs e)
{
//using TextBoxBase properties/methods like SelectAll();
}
}
Run Code Online (Sandbox Code Playgroud)
然后
class SpecializedTB : CommonFeatures<TextBox>
{
// using properties/methods specific to TextBox
protected override void OnTextChanged(TextChangedEventArgs e)
{
... base.OnTextChanged(e);
}
}
Run Code Online (Sandbox Code Playgroud)
和
class SpecializedRTB : CommonFeatures<RichTextBox>
{
// using methods/properties specific to RichTextBox
}
Run Code Online (Sandbox Code Playgroud)
不幸
class CommonFeatures<T> : T where T : TextBoxBase …Run Code Online (Sandbox Code Playgroud)