我正在創建一個應用程式,該應用程式回傳要在各種條件下使用的金屬串列。我有一個金屬類,然后為每種型別的金屬(如鋼、鋁等)分類。如果我有一個不同鋼的串列,我想首先根據所有金屬共有的一組屬性選擇最好的,然后再做第二個通過基于鋼的獨特屬性。(這不是我的確切問題,但我的問題是類似的。)
我不知道如何將 List<Steel> 傳遞給 Metal 類的 GetBest() 方法,如下所示,該方法采用 List<Metal> 型別的第一個引數。由于下面用 ** 突出顯示的行中的錯誤,代碼無法編譯:“引數 1:無法從 'System.Collections.Generic.List<Steel>' 轉換為 'System.Collections.Generic.List<Metal>' .
public class Metal {
public int PropA { get; set; }
public List<Metal> GetBest( List<Metal> list, int condition1 )
{
var best = new List<Metal>();
//Analysis code here...
return best;
}
}
public class Steel : Metal
{
public int PropB { get; set; }
public List<Steel> GetBest(List<Steel> list, int condition1, int condition2 ) {
var bestSteel = new List<Steel>();
//Do first pass selection based on properties of all metals.
**bestSteel = Metal.GetBest(list, condition1);**
//Do some additional analysis based to Steel's unique properties.
//Analysis code here...
return bestSteel;
}
uj5u.com熱心網友回復:
您可以使用受約束的泛型方法:
public static List<T> GetBest<T>(List<T> list, int condition1) where T : Metal
{
var best = new List<T>();
// Analysis code here...
return best;
}
uj5u.com熱心網友回復:
我要回答一個不同的問題!看看我如何在不混淆我的物件(Metal, Steel)的情況下解決這個問題,我的邏輯是根據某些條件選擇最好的金屬:
public class Metal{}
public class Steel:Metal{}
public class MetalPickerContext
{
public int Condition1{ get;set;}
}
public class MetalPicker<TMetal, TContext>
where TMetal: Metal
where TContext: MetalPickerContext
{
public virtual IEnumerable<TMetal> GetBest(IEnumerable<TMetal> list, TContext context)
{
var result = new List<TMetal>();
// logic for picking the best metal based on Condition1
return result;
}
}
public class SteelPickerContext: MetalPickerContext
{
public int Condition2{get;set;}
}
public class SteelPicker : MetalPicker<Steel,SteelPickerContext>
{
public override IEnumerable<Steel> GetBest(IEnumerable<Steel> list, SteelPickerContext context)
{
var initialResult = base.GetBest(list,context);
// Having called the base logic apply more with reference to Condition2
return initialResult;
}
}
這會編譯(如您在此處看到的),并且我可以稍微擴展一下示例,給出更多細節以使其成為可行的示例。讓我知道這是否對您有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405260.html
標籤:
上一篇:泛型回傳Nil為泛型型別
