Rah*_*han 3 c# generics constructor constraints
我有以下winforms类:
class EntityEditorForm<T>: System.Windows.Forms.Form
where T: ICloneable<T> {}
class EntityCollectionEditorForm<T> : System.Windows.Forms.Form
where T: ICloneable<T> {}
Run Code Online (Sandbox Code Playgroud)
第一个表单类是一个编辑器,用于<T>在运行时根据T的类型创建控件.
第二个是一个管理器,用于收集<T>和添加,编辑和删除功能.该集合显示在listview控件中,其中使用自定义属性通过反射填充字段.
"添加"和"编辑"按钮的代码如下所示:
private void buttonEdit_Click (object sender, System.EventArgs e)
{
T entity = default(T);
entity = (T) this.listView.SelectedItems[0].Tag;
new EntityEditor<T>(entity).ShowDialog(this);
}
private void buttonEdit_Click (object sender, System.EventArgs e)
{
T entity = new T(); //This is the code which is causing issues
entity = (T) this.listView.SelectedItems[0].Tag;
new EntityEditor<T>(entity).ShowDialog(this);
}
Run Code Online (Sandbox Code Playgroud)
将default(T)在编辑的情况下工作,但我在与添加的场景麻烦.T entity = new T();看似不合法.
如果您的类型包含无参数构造函数,则可以在泛型类型上添加约束T以允许通过此无参数构造函数进行实例化.为此,请添加约束:
where T : new()
Run Code Online (Sandbox Code Playgroud)
关于类型参数约束的 MSDN文章.
| 归档时间: |
|
| 查看次数: |
1605 次 |
| 最近记录: |