2012-11-20 44 views
1

我对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); 
} 

但是,那给了我错误说'类型或命名空间名称不能b发现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(GC1 ass2)时,我无法更改访问修饰符。

我也得到一个奇怪的错误说“GClass1.GetKeyForItem(GClass2)”必须声明主体,因为它不标记为抽象,EXTERN或部分”

是否有任何解决方法访问修饰符的问题,并有人可以解释'申报一个机构,因为它没有标记'错误?

谢谢!

+2

我建议在阅读一本好书C#并重新开始。正如你已经经历过的那样,这些快速修复只会导致更多的问题。 –

回答

2

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

这应该编译:

protected override string GetKeyForItem(GClass2 item) 
{ 
    throw new NotImplementedException(); 

    // to implement, you'd write "return item.SomePropertyOfGClass2;" 
} 
0

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

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

即使它什么都不做。

2

您需要完全按照定义来实现抽象方法。如果你想要一个方法是公开访问,而不必只是protected无障碍它定义,你需要添加一个新的,独立的,方法是使用它:

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

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