【问题标题】:Changing access modifiers workaround更改访问修饰符解决方法
【发布时间】:2012-11-20 18:23:42
【问题描述】:

我对 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 是受保护的。新错误告诉我在覆盖 System.Collections.ObjectModel.KeyedCollection.GetKeyForItem(GCl‌​ass2) 时无法更改访问修饰符。

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

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

谢谢!

【问题讨论】:

  • 我建议阅读一本关于 C# 的好书,然后重新开始。正如您已经亲身经历的那样,这些快速修复只会导致更多问题。

标签: c#


【解决方案1】:

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

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

    public string GetKey(GClass2 item)
    {
        return GetKeyForItem(item);
    }
}

【讨论】:

    【解决方案2】:

    GetKeyForItem 在基本抽象类中受到保护,因此它必须在派生类中受到保护。 (另外,我想你会想要实现它——这是你的第二个错误的根源,因为方法必须有一个主体,除非它们是抽象的。)

    这应该编译:

    protected override string GetKeyForItem(GClass2 item)
    {
        throw new NotImplementedException();
    
        // to implement, you'd write "return item.SomePropertyOfGClass2;"
    }
    

    【讨论】:

      【解决方案3】:

      错误'GClass1.GetKeyForItem(GClass2)' must declare a body because it is not marked abstract, extern, or partial' 可能意味着您需要实现该方法,而不是简单地在您的类中声明它。其实你需要在里面加一段代码

      protected override string GetKeyForItem(GClass2 item)
      {
           // some code
      }
      

      即使它什么都不做。

      【讨论】:

        猜你喜欢
        • 2015-10-14
        • 2012-03-08
        • 2015-09-16
        • 2012-10-22
        • 2014-09-08
        • 1970-01-01
        • 2016-03-12
        • 2010-11-13
        • 2013-10-19
        相关资源
        最近更新 更多