簡體   English   中英

泛型在類和方法上看起來並不相同

[英]Generics appear not to be the same in class and method

之前我問過這個問題,但它被擱置了,因為這個問題是一個“簡單”的轉換問題。 對我來說,這不是。 這是我第一次嘗試使用泛型。

我有一個像這里的代碼Class沒有任何錯誤:

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; }
}

接着我用這個Class來傳遞許多不同的數據之間的Classes開始用下面的代碼:

public static T Show<T>(DependencyObject sender, MessageBoxIcon icon, string caption, ObservableCollection<T> dataSource, MessageBoxButton button) where T : IComparable<T>, new()
{
    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));
}

可以編譯此代碼而不會出現任何錯誤。 如果我說where T : IComparable<T>需要在Method使用T而且額外的, new()需要, new()來在new GridBox<T>使用它,我是對的嗎? 再次,第一次嘗試仿制葯。

上面調用Show<T>代碼如下:

internal class GridBoxViewModel<T> : BoxBaseViewModel // where T : new()
{
    public T Show<T>(GridBox<T> gridBox)
    {
        // Set content item
        DataSource = gridBox.DataSource;

        // Set visual items and block the excecution code 
        AddView(gridBox.Grid, gridBox.View, gridBox.Icon, gridBox.Caption, gridBox.Button);

        // Return value
        return SelectedItem;
    }

    public ObservableCollection<T> DataSource { get; set; }
    public T SelectedItem { get; set; }
}

這里出現了問題。 DataSource = gridBox.DataSource給出一個錯誤,它無法將System.Collections.ObjectModel.ObservableCollection<T>轉換為System.Collections.ObjectModel.ObservableCollection<T> ,這在我看來是相同的。 兩者都指的是相同的Class Library [C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.5\\System.dll]

第二個問題是return SelectedItem; 這里的錯誤幾乎相同,但有點不同。 它無法將'T'轉換為'T [Controls\\ViewModels\\GridBoxViewModel.cs(6)]'

對我來說,明顯的原因是, Tinternal class GridBoxViewModel<T> : BoxBaseViewModel是不一樣的T如在public T Show<T>(GridBox<T> gridBox) 這實際上是原因,如果是這樣,我該如何處理這個問題並修復它?

Show刪除泛型參數:

public T Show(GridBox<T> gridBox)

T類型參數與類上聲明的參數不同,這就是編譯器出錯的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM