我在使用隱式轉換和IEnumerable時遇到了一個有趣的情況 - 請看附加代碼的最後一行 - 它不會編譯。隱式轉換IEnumerable轉換爲泛型
public class Outer<T>
{
private T field;
public Outer(T it)
{
field = it;
}
public static implicit operator Outer<T> (T source)
{
return new Outer<T>(source);
}
}
void Main()
{
Outer<string> intsample = "aa";
Outer<IList<object>> listsample = new List<object>();
//The line below fails with:
//CS0266 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<object>'
//to 'UserQuery.Outer<System.Collections.Generic.IEnumerable<object>>'.
//An explicit conversion exists (are you missing a cast?)
Outer<IEnumerable<object>> enumerablesample = Enumerable.Empty<object>();
}
我有一個很強烈的直覺,它是興高采烈的IEnumerable
是協變,但也有人更正式的解釋?
爲什麼不直接投射? – Mafii
因爲這只是示例來顯示問題,所以如果使用像LangugeExt和它的任一類型的庫,隱式轉換非常方便。不幸的是,我不明白將它標記爲重複,並指出關於方差和遺傳的不是如此相關的答案。 –
@PatrickHofman我必須同意,這個問題不是直接由重複的答案。投票重新開放。 – Mafii