我有以下課程:
- Parameter.cs(泛型)
- CurrentLod.cs(具體型別,繼承自Parameter)
這是 Parameter.cs 的當前類定義
public abstract class Parameter<T> where T: IComparable{
// class methods...
}
然后是 CurrentLod.cs 的類定義
public class CurrentLod : Parameter<String>{
// Constructor
public CurrentLod() : base()
}
然后,在第三個檔案中
new List<Parameter<IComparable>>() { new CurrentLod() }
前面的代碼無法編譯,編譯器顯示錯誤資訊:“Cannot convert from CurrentLod to Parameter”
我相信它與協變和逆變有關,但我仍然不清楚。
uj5u.com熱心網友回復:
您List<T>被定義為接受任何Parameter<IComparable>. CurrentLod是 的特定型別Parameter<IComparable>,即 a Parameter<String>。
我們稍后可能會定義另一種型別Foo : Parameter<Int32>,因為Int32也實作了IComparable。
但是將 a 添加Foo到 s 串列中意味著什么CurrentLod?
為了解決您的問題,您可以為您的引數型別創建一個非泛型基類或介面,并將其用作 List 的型別,例如:
public abstract class Parameter
{
// Common paramater operations/properties. This could be an interface.
}
public class Parameter<T> : Parameter where T : IComparable
{
// Type-specific generic members.
}
public class Int32Parameter : Parameter<Int32>
{
// Int32 Parameter implementation
}
public class StringParameter : Parameter<String>
{
// String Parameter implementation
}
// This unit test will compile and pass
public class UnitTest1
{
[Fact]
public void Test1()
{
var l = new List<Parameter>();
l.Add(new StringParameter());
l.Add(new Int32Parameter());
Assert.Equal(2, l.Count);
}
}
現在 List 被定義為包含一個特定的型別。當您從串列中檢索一個專案時,您需要測驗它的具體型別是什么并適當地轉換它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/418934.html
標籤:
上一篇:PowerShell硬碟驗證程式
下一篇:SqlDeveloper日期比較
