我希望添加这些接口(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/