我想用通用接口(interface) IAppcontextItem 实现一个通用类 AppContextItem。因为我想在不知道确切类型的情况下将多个 AppContextItems 存储在列表中(而且我希望能够在列表中混合使用多个类型的 AppContextItems)。我创建了另一个非通用接口(interface) IAppContextItem。 IAppContextItem 的通用实现应该隐藏非通用字段,但不知何故却没有,因为我收到一个编译错误,告诉我需要使用返回类型对象实现 Element。是不可能做我想做的事还是我做错了什么?
IAppcontextItem.cs
public interface IAppContextItem
{
string Key { get; set; }
object Element { get; set; }
}
public interface IAppContextItem<T> : IAppContextItem
where T : class
{
new string Key { get; set; }
new T Element { get; set; }
}
AppContextItem.cs
public class AppContextItem<T> : IAppContextItem<T> where T : class
{
private string key = string.Empty;
private T element;
public string Key
{
get { return key; }
set { key = value; }
}
public T Element
{
get { return element; }
set { element = value; }
}
最佳答案
您必须同时实现 T Elemen
t 和 object Element
特性。 object Element
的实现看起来像:
object IAppContextItem.Element
{
get; set;
}
然后您可以将其转换为正确的接口(interface):
AppContextItem<MainApp> app = new AppContextItem<MainApp>();
IAppContextItem iapp = (IAppContextItem)app;
object o = iapp.Element;
这叫做 Explicit Interface Implementation .
如果你想有一个不同的实现 IAppContextItem.Key
和 IAppContextItem<T>.Key
您可以像这样使用显式接口(interface)实现:
string IAppContextItem.Key
{
get { return key + "A"; }
set { key = value; }
}
string IAppContextItem<T>.Key
{
get { return key + "B"; }
set { key = value; }
}
关于c# - 父非通用接口(interface)方法的通用接口(interface)隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9197465/