Skip to main content
 首页 » 编程设计

c#之更改访问修饰符解决方法

2024年02月20日15dyllove98

我是 C# 的新手,如果这是一个愚蠢的问题,请原谅我。我遇到错误,但我不知道如何解决。我正在使用 Visual Studio 2010。我已经从社区成员那里实现了几个修复程序,但问题似乎不断出现。

从这行代码开始

public class GClass1 : KeyedCollection<string, GClass2> 

我报错了

'GClass1' does not implement inherited abstract member 'System.Collections.ObjectModel.KeyedCollection<string,GClass2>.GetKeyForItem(GClass2)' 

据我所知,这可以通过像这样在继承类中实现抽象成员来解决

public class GClass1 : KeyedCollection<string, GClass2> 
{ 
  public override TKey GetKeyForItem(TItem item); 
  protected override void InsertItem(int index, TItem item) 
  { 
    TKey keyForItem = this.GetKeyForItem(item); 
    if (keyForItem != null) 
    { 
        this.AddKey(keyForItem, item); 
    } 
    base.InsertItem(index, item); 
} 

但是这给了我错误提示“找不到类型或命名空间名称 TKey/TItem 找不到。”所以我替换了占位符类型。

目前代码是

public class GClass1 : KeyedCollection<string, GClass2> 
{ 
 
  public override string GetKeyForItem(GClass2 item); 
  protected override void InsertItem(int index, GClass2 item) 
  { 
    string keyForItem = this.GetKeyForItem(item); 
    if (keyForItem != null) 
    { 
      this.AddKey(keyForItem, item); 
    } 
  base.InsertItem(index, item); 
 } 

我完全忘记了 GetKeyForItem 是 protected 。新错误告诉我在覆盖 System.Collections.ObjectModel.KeyedCollection.GetKeyForItem(GCl‌ ass2) 时无法更改访问修饰符。

我还收到一个奇怪的错误,说“GClass1.GetKeyForItem(GClass2)”必须声明一个主体,因为它没有标记为抽象、外部或部分

访问修饰符问题是否有任何解决方法,有人可以解释“声明主体因为它未标记”错误吗?

谢谢!

请您参考如下方法:

您需要完全按照定义的方式实现抽象方法。如果您希望该方法可公开访问,而不是仅仅具有它定义的 protected 可访问性,您需要添加一个新的、单独的、使用它的方法:

public class GClass1 : KeyedCollection<string, GClass2> 
{ 
    protected override string GetKeyForItem(GClass2 item) 
    { 
        throw new NotImplementedException(); 
    } 
 
    public string GetKey(GClass2 item) 
    { 
        return GetKeyForItem(item); 
    } 
}