c# - 这个派生接口(interface)getter有什么歧义?

标签 c# inheritance interface

我希望添加这些接口(interface):

public interface IIndexGettable<TKey, TValue>
{
    TValue this[TKey key]{ get; }
}

public interface IIndexSettable<TKey, TValue>
{
    TValue this[TKey key]{ set; }
}

public interface IIndexable<TKey, TValue> : IIndexGettable<TKey, TValue>, IIndexSettable<TKey, TValue>
{   
  // new TValue this[TKey key]{ get; set; } // as suggested by SO question 1791359 this will "fix" the issue.
}

然后当我尝试使用 IIndexable的 setter/getter ,我得到以下编译器错误:

The call is ambiguous between the following methods or properties: 'IIndexGettalbe<TKey, TValue>.this[Tkey]' and 'IIndexSettable<TKey, TValue>.this[TKey]'

这是我运行的代码:

public static class IIndexableExtensions
 {
    public static Nullable<TValue> AsNullableStruct<TKey, TValue>(this IIndexable<TKey, object> reader, TKey keyName) where TValue : struct
    {
        if (reader[keyName] == DBNull.Value) // error is on this line.
        {
            return null;
        }
        else
        {
            return (TValue)reader[keyName];
        }
    }   
 }

它不应该明确地继承 IIndexGettable 的 getter 和 IIndexSettable 的 setter 吗?

顺便说一句,我并不是要让这种声音对语言设计产生煽动性。我确信这背后有一个很好的理由,我的目标是了解原因是什么,以便更好地理解语言。

最佳答案

尝试了下面的代码,它工作正常。你的错误场景是什么?此代码中没有什么?

class Program
    {
        static void Main(string[] args)
        {
            Foo<int, string> foo = new Foo<int, string>();
            foo.dict.Add(1, "a");
            foo.dict.Add(2, "b");
            Console.WriteLine(((IIndexGettable<int, string>)foo)[1]);
            ((IIndexSettable<int, string>)foo)[3] = "c";
            Console.WriteLine(foo[3]);
            Console.ReadLine();
        }
    }

    public interface IIndexGettable<TKey, TValue>
    {
        TValue this[TKey key] { get; }
    }

    public interface IIndexSettable<TKey, TValue>
    {
        TValue this[TKey key] { set; }
    }

    public interface IIndexable<TKey, TValue> : IIndexGettable<TKey, TValue>, IIndexSettable<TKey, TValue>
    {

    }

    public class Foo<TKey, TValue> : IIndexable<TKey, TValue>
    {
        public Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
        public TValue this[TKey key]
        {
            get
            {
                return dict[key];
            }

            set
            {
                dict[key] = value;
            }
        }

    }

关于c# - 这个派生接口(interface)getter有什么歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33287125/

相关文章:

c# - 将匿名类型转换为接口(interface)?

c# - 如何按顺序从字符串中获取找到的字符并保留重复项以将其添加到列表中而不覆盖以前的字符

java - Scala非法继承错误没有意义

java - 尝试从子级序列化父级成员变量,其中父级未实现可序列化

php - 如何使用继承来传递查询?

java - 实现类或导入类java

c# - 为什么现在类倾向于定义为接口(interface)?

c# - 比较数据库中的日期时间时,“LIKE%”在更新查询中不起作用

c# - 实现 IComparable 时,为什么相同的项目不始终按相同的顺序放置

c# - 未知服务器标记 'EPiServerUI:ToolButton'