2014-06-20 21 views
2

所以,我有一个类:如何使用泛型

internal class GridBox<T> : BoxBase where T : new() 
{ 
    public GridBox(Grid grid, GridBoxView view, MessageBoxIcon icon, string caption, ObservableCollection<T> dataSource, MessageBoxButton button) 
     : base(grid, icon, caption, button) 
    { 
     View = view; 
     DataSource = dataSource; 
    } 

    public GridBoxView View { get; set; } 
    public ObservableCollection<T> DataSource { get; set; } 
} 

我用这个GridBoxClass这里:

public static T Show<T>(DependencyObject sender, MessageBoxIcon icon, string caption, ObservableCollection<T> dataSource, MessageBoxButton button) where T : IComparable<T> 
    { 
     Window window = Window.GetWindow(sender); 
     Grid grid = Extensions.FindChild<Grid>(window); 
     GridBoxView gridBox = new GridBoxView(); 

     return gridBox.Show<T>(new GridBox<T>(grid, gridBox, icon, caption, dataSource, button)); 
    } 

我这里得到一个错误寿在new GridBox<T>

'T'必须是一个具有公共无参数构造函数的非抽象类型,以便在泛型类型或方法中将其用作参数'T'

那么,如果T来自public static T Show<T>,我该如何使用new GridBox<T>

回答

4

GridBox<T>T一个约束需要类型有一个公共的无参数构造函数。这是where T : new()指定的内容。 (见MSDN article on the new constraint

这样,当你试图在你的Show的方法来使用它,在T必须仍然满足该条件。如果您更新Show方法:

public static T Show<T>(DependencyObject sender, MessageBoxIcon icon, string caption, ObservableCollection<T> dataSource, MessageBoxButton button) 
    where T : IComparable<T>, new() 

通过添加new()约束Show,你会满足约束GridBox为好。

1

您需要添加new约束:

public static T Show<T>(DependencyObject sender, MessageBoxIcon icon, string caption, ObservableCollection<T> dataSource, MessageBoxButton button) where T : IComparable<T>, new() 
+0

所有的答案都是正确的,但只能选择1作为答案,对不起。 – Krowi

4

GridBox的泛型参数应用了一个你不需要的约束,这意味着如果允许编译这个约束,你就可以传入一个不符合约束的类型。解决方法是当然简单,约束添加到通用的说法,类型需要有一个无参数的构造函数:

public static T Show<T>(...) where T : IComparable<T>, new() 
+0

所有的答案都是对的,但只能选择1作为答案,对不起。 – Krowi

1

你需要新的()约束添加到您的静态功能以及:

public static T Show<T>(DependencyObject sender, MessageBoxIcon icon, string caption, ObservableCollection<T> dataSource, MessageBoxButton button) where T : IComparable<T>, new() 
+0

所有答案都是对的,但只能选择1作为答案,对不起。 – Krowi