2016-05-23 42 views
0

我試圖組建一個架構是這樣的:參數 'SpecificGroupType1' 是不能分配給參數類型'<IItem>集團

    • 集團
      • 項目
        • 屬性
        • 屬性
    • 集團
      • 項目
        • 屬性
        • 屬性
  • [...]

我再試圖實例化這個架構是這樣的:

var sections = new List<ISection> 
{ 
    new Section("Section Header", new List<Group<IItem>> 
    { 
     new SpecificGroupType1(token, "GroupName") 
    } 
}; 

的SpecificGroupType1然後旋轉起來適當的iItem的新列表類型。

我收到以下錯誤,但:

Argument SpecificGroupType1 is not assignable to parameter type Group<IItem> 

我不明白爲什麼,但是,因爲SpecificGroupType1從集團繼承。

完整的架構看起來像這樣(我省略了IAttribute的東西,因爲我跑步進入發行前IAttribute東西也不甘寂寞發生):

Section.cs

public interface ISection { // Stuff } 

public class Section : ISection 
{ 
    public Section(string sectionName, IList<Group<IItem>> groups) 
    { 
     Name = sectionName; 
     Groups = groups; 
    } 
} 

Group.cs

public interface IGroup { // Stuff } 

public abstract class Group<T> : IGroup where T : IItem 
{ 
    protected Group(JToken token, string groupName) 
    { 
     Name = groupName; 
     Items = new List<IItem>(); 

     foreach (var itemToken in Token.Children()) 
     { 
      Items.Add((Item)Activator.CreateInstance(typeof(T), itemToken); 
     } 
    } 

    public string Name { get; internal set; } 
    public JToken Token { get; internal set; } 

    protected IList<IItem> Items { get; set; } 
} 

SpecificGroupType1.cs

public class SpecificGroupType1 : Group<SpecificItemType1> 
{ 
    public SpecificGroupType1(JToken token, string groupName) : base(token, groupName) {} 

    // Stuff 
} 

Item.cs

public interface IItem { // Stuff } 

public abstract class Item : IItem 
{ 
    protected ConfigurationItem(JToken token) 
    { 
     Attributes = new List<IAttribute>(); 
     Token = token; 
    } 

    public IList<IAttribute> Attributes { get; set; } 
    public JToken Token { get; set; } 
} 

SpecificItemType1。cs

public class SpecificItemType1 : Item 
{ 
    public SpecificItemType1(JToken token) : base(token) {} 

    // Stuff 
} 
+0

我在代碼中看到的一個問題是您有'IGroup ',但是'IGroup'的聲明沒有通用參數。這將無法編譯,除非另有通用接口定義。 – recursive

+0

哎呀,那是一個錯字。這實際上是IList >在我的代碼中。 – jrsowles

+0

得到SpecificItemType1的定義?它是否繼承了Item? – Bill

回答

2

基本上,這是您的通用參數的問題。考慮這個簡化的例子。

// does not compile 
Group<IItem> g = new SpecificGroupType1(token, "GroupName"); 

// does compile 
Group<SpecificItemType1> g = new SpecificGroupType1(token, "GroupName"); 

的問題是,SpecificGroupType1實現類Group<SpecificItemType1>,這是不一樣Group<IItem>。如果您希望能夠以這種方式使用更多派生的泛型參數類型,則需要使用協變泛型參數聲明。在C#中,只能在接口上使用,而不能在類中使用,因此您可能需要重構一下。這將是這樣的。

interface IGroup<out T> : IGroup where T: IItem { 
    // declarations 
} 

請注意out關鍵字。

相關問題