【发布时间】: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<GenericComboBoxItem> 转换为 List<IComboBoxItem>。
我最初在使用从GenericComboBoxItem 继承的类时遇到了这个问题,并认为我只需要使用和接口而不是继承,但后来发现两个类都失败并在那里找到了,但是我错过了一些技巧在这里。
这可能是重复的东西,但我花了一个上午的时间搜索,但没有运气,我想我会发布一个新问题。
非常感谢任何帮助!
【问题讨论】:
-
看看 C# 中的泛型协变和逆变
-
正如
public TransactionModalVM(List<IComboBoxItem> categoryList)所指定的,TransactionModalVM 想要一个可以包含任何 类型的IComboBoxItem 元素的列表。然而,您尝试提供一个列表,该列表仅 包含 GenericComboBoxItem 元素。轰隆隆!通过在您的 GetTransactionModalVM 方法中创建new List<IComboBoxItem>() { new GenericComboBoxItem(...) }让 TransactionModalVM 满意。 -
哦!谢谢@elgonzo!!