相关疑难解决方法(0)

C#中的C++样式模板,可能以任何方式?

我希望每种基本类型都有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)

.net c# c++ generics templates

12
推荐指数
2
解决办法
1644
查看次数

C#通用继承解决方法

例:

我想要从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)

c# generics inheritance

2
推荐指数
1
解决办法
2038
查看次数

标签 统计

c# ×2

generics ×2

.net ×1

c++ ×1

inheritance ×1

templates ×1