c# Indexer属性——任何虚拟化get方法而不是set方法的方法

本文关键字:方法 set get Indexer 属性 任何 虚拟化 | 更新日期: 2023-09-27 18:01:42

我有一个特殊类型的字典。我不确定如何做到这一点,但我希望使get方法虚拟,但不是set方法:

    public TValue this[TKey key]
    {
        get { ... }
        set { ... }
    }

可能吗?如果可能,正确的组合是什么?

c# Indexer属性——任何虚拟化get方法而不是set方法的方法

你不能这样做直接 -你需要添加一个单独的方法:

protected virtual TValue GetValue(TKey key) { ...}
public TValue this[TKey key]
{
    get { return GetValue(key); }
    set { ... }
}

抱歉…在c#中没有这样做的语法,但你可以这样做。

public TValue this[TKey key]
{
   get { return GetValue(key) }
   set { ... }
} 
protected virtual TValue GetValue(TKey key)
{
   ...
}

我可能会误解一些东西,但如果你的Dictionary将是只读你必须实现一个包装器,以确保它真正readony(字典的索引属性不是虚拟,所以你不能覆盖它的行为),在这种情况下,你可以做以下:

public class ReadOnlyDictionary<TKey, TValue>
{
    Dictionary<TKey, TValue> innerDictionary;
    public virtual TValue this[TKey key]
    {
        get
        {
            return innerDictionary[key];
        }
        private set
        {
            innerDictionary[key] = value;
        }
    }
}

我想你在这里要做的是创造一种情况,他们必须定义如何读取属性,而不是如何设置属性?

我觉得这是个坏主意。你可以有一个设置来设置_myVar的值但是最终开发者要构造一个getter来读取_someOtherVar。也就是说,我不知道您的用例是什么,所以很可能我遗漏了一些东西。

无论如何,我认为前面的问题可能会有所帮助:为什么不可能重写getter-only属性并添加setter?