2011-06-17 26 views
0

我有一個更復雜的問題,但我已經熬下來到下面這個簡單的例子:接口繼承和通用接口強制顯式強制轉換?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Sandbox 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      IFactory<IProduct> factory = new Factory(); 
     } 
    } 

    class Factory : IFactory<Product> 
    { 

    } 

    class Product : IProduct 
    { 

    } 

    interface IFactory<T> where T : IProduct 
    { 

    } 

    interface IProduct 
    { 

    } 
} 

一切都很好,花花公子......除了我得到這個錯誤。

錯誤1無法隱式轉換類型Sandbox.FactorySandbox.IFactory<Sandbox.IProduct>。存在明確的轉換(您是否缺少演員?)c:\ ~~ \ Program.cs 12 42沙盒

任何人都願意提供洞察,爲什麼會出現這種情況?我確信Jon Skeet或Eric Lippert可以在心裏解釋爲什麼會出現這種情況,但必須有人不僅能夠理解爲什麼這不能被推斷,而是能夠解釋如何最好地解決這種情況。

跟進問題here

+0

事實證明,Eric Lippert和Jon Skeet在很多次的心跳中都解釋了這一點。如果你搜索'interface + covariance',你可能會絆倒並找到一個這樣的解釋。 –

+0

編輯,隨訪。 – Firoso

+1

後續問題應作爲單獨的問題提出(儘管將它們鏈接在一起) –

回答

3

這是因爲FactoryIFactory< Product>和你是在分配給一個IFactory< IProduct>,由於IFactorycovariant,你可以不投泛型亞型到一個通用的超類型。

試着製作IFactory< out T>,這應該使下列分配工作。

編輯

@Firoso,在你的工廠接口,你要創建一個列表,您可以在其中寫入。如果您的接口是協變的,你不能寫任何東西,因爲以下幾點:

List<object> list = new List<string>(); //This is not possible by the way 
list.Add(new {}); //Will fail here because the underlying type is List<string> 

你應該在你的情況下忽略協方差和剛剛創建分配給IFactory<Product>代替或更改出廠繼承IFactory<IProduct>相反,我建議後者,但這取決於你

+0

哦,這是一個協變問題,這是有道理的:-P – Firoso

+0

後續問題添加。 – Firoso

+0

追加答案已添加。 –