<T>如果在編譯時已知并且在運行時不會更改,是否可以使用另一個類的型別在泛型類中設定型別?
例如,我的應用中有很多 3rd 方 UI 網格。每個網格都有幾種型別的事件回呼引數,它們在處理程式方法中回傳。它們都是泛型,并且得到它們所顯示的類。
我有許多網格顯示具有許多相同方法的不同型別,并且我正在嘗試進行簡化,以便我的樣板設定可以通過在一個地方更改所需的類來完成。
現有代碼:
Comment selectedComment; //Comment is type that is displayed in grid and all args
Grid<Comment> commentGrid;
void RowSelected(RowSelectEventArgs<Comment> args)
{
// Some code here
}
所需代碼(示例不起作用
Comment selectedComment; //Comment is type that is displayed in grid and all args
Type type = typeof(selectedComment); //I want to use some sort of line to set all <T> in one spot
Grid<type> commentGrid; //Is it possible to refers <T> to the holder variable 'type' above?
void RowSelected(RowSelectEventArgs<type> args)
{
// Some code here
}
//Both sections that say <type> give error: The type or namespace could not be found.
uj5u.com熱心網友回復:
您可以在檔案頂部使用using別名指令,它將定義該檔案中任何地方的型別。
using T = MyNamespace.Comment;
T selectedComment;
Type type = typeof(T);
Grid<T> commentGrid;
void RowSelected(RowSelectEventArgs<T> args)
{
// Some code here
}
T 可能是一個糟糕的選擇,您可能想要一些更具描述性的內容
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/363412.html
上一篇:是否可以僅限制記錄的方法?
下一篇:Ktor具體化型別引數
