c# - 父非通用接口(interface)方法的通用接口(interface)隐藏

标签 c# .net

我想用通用接口(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.KeyIAppContextItem<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/

相关文章:

c# - 如何保存文本框中的第一个文本而不覆盖它 C# .NET

.net - .net 中是否有用于手写识别的开源库?

.net - 我需要 WPF 4 的 Accordion 控件

c# - LINQ 查询,使用分组依据选择最新值 - 不支持的方法

c# - Microsoft Graph 订阅扩展错误 - 删除/更新

c# - 如何将 jQuery 函数放入我的代码后面?

c# - 在 Excel 中调用 Cells.End

c# - 将多个整数打包和解包到 Uint64 中或从 Uint64 中解包

c# - ConcurrentBag<T> 实现中是否存在内存泄漏?

c# - Autofixture:如何以声明的方式表达以下代码?