在列表<iclass>中使用Class作为接口

时间:2018-11-25 20:23:15

标签: c# list interface casting

我在尝试使用接口列表时遇到问题。 (我可能很难解释这一点,我现在才编码一年,但是可以。)

我有一个界面:

public interface IComboBoxItem
{
    string Display { get; set; }
    int? IntValue { get; set; }
    string StringValue { get; set; }
}

还有一个实现该接口的类:

public class GenericComboBoxItem : IComboBoxItem
{
    public virtual string Display { get; set; }
    public virtual int? IntValue { get; set; }
    public virtual string StringValue { get; set; }

    public GenericComboBoxItem(string stringValue)
    {
        Display = stringValue;
        StringValue = stringValue;
        IntValue = null;
    }
}

然后,在我的视图模型的构造函数中列出这些列表:

public class TransactionModalVM
{
    public TransactionModalVM(List<IComboBoxItem> categoryList)
    {
        CategoryList = categoryList;
    }

    public List<IComboBoxItem> CategoryList { get; set; }
}

但是,当我尝试将它们传入

public class TransactionsOM
{
    internal TransactionModalVM GetTransactionModalVM()
    {
        return new TransactionModalVM(new List<GenericComboBoxItem>() { new GenericComboBoxItem("Not yet Implemented") });
    }
}

我收到一个错误,它无法从List<GenericComboBoxItem>转换为List<IComboBoxItem>

当我使用从GenericComboBoxItem继承的类时,我最初遇到了这个问题,并以为我只需要使用接口而不是继承,但是后来发现这两个类都失败了,并且想出了办法,但是我有些窍门。我在这里不见了。

这可能是某些东西的重复,但是我整日没有运气地搜索,并且以为我会发一个新问题。

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

研究C#中的协方差和协方差是一个好主意。

但是,在您的特定情况下,在视图模型中使用IReadOnlyList而不是列表将解决您的问题。

public class TransactionModalVM
{
    public  TransactionModalVM(IReadOnlyList<IComboBoxItem> categoryList)
    {
        CategoryList = categoryList;
    }

public IReadOnlyList<IComboBoxItem> CategoryList { get; set; }
}

List<GenericComboBoxItem>可转换为IReadOnlyList<IComboBoxItem>,但不能转换为List<IComboBoxItem>