【问题标题】:Use Class as interface in List<IClass> [duplicate]在 List<IClass> 中使用 Class 作为接口 [重复]
【发布时间】:2018-11-25 20:23:14
【问题描述】:

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

我有一个界面:

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;
    }
}

然后我在 View Model 的构造函数中列出这些:

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&lt;GenericComboBoxItem&gt; 转换为 List&lt;IComboBoxItem&gt;

我最初在使用从GenericComboBoxItem 继承的类时遇到了这个问题,并认为我只需要使用和接口而不是继承,但后来发现两个类都失败并在那里找到了,但是我错过了一些技巧在这里。

这可能是重复的东西,但我花了一个上午的时间搜索,但没有运气,我想我会发布一个新问题。

非常感谢任何帮助!

【问题讨论】:

  • 看看 C# 中的泛型协变和逆变
  • 正如public TransactionModalVM(List&lt;IComboBoxItem&gt; categoryList) 所指定的,TransactionModalVM 想要一个可以包含任何 类型的IComboBoxItem 元素的列表。然而,您尝试提供一个列表,该列表 包含 GenericComboBoxItem 元素。轰隆隆!通过在您的 GetTransactionModalVM 方法中创建 new List&lt;IComboBoxItem&gt;() { new GenericComboBoxItem(...) }TransactionModalVM 满意。
  • 哦!谢谢@elgonzo!!

标签: c# list interface casting


【解决方案1】:

在 C# 中研究协变和逆变是个好主意。

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

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

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

List&lt;GenericComboBoxItem&gt; 可转换为 IReadOnlyList&lt;IComboBoxItem&gt;,但不能转换为 List&lt;IComboBoxItem&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-17
    • 2019-04-05
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多