[英]Non-virtual, non-abstract method causing “C# virtual or abstract members cannot be private”
錯誤1'Interface.myDerivedClass.myMethod()':虛擬或抽象成員不能為私有c:\\ users \\ igmfun \\ documents \\ visual studio 2012 \\ Projects \\ Interface \\ Interface \\ Program.cs 16
將虛擬或抽象成員設為私有會使其他類(包括派生類)無法訪問它,從而無法覆蓋該方法,從而使其虛擬或抽象質量變得毫無意義。 我知道了。
但是等等...編譯器抱怨的是派生類中的成員,而不是基類...而且我從未將成員聲明為虛擬或抽象...上覆的成員(派生類中的成員)也是如此。從被重寫的虛擬或抽象成員繼承虛擬或抽象質量?
另外,如果我改變
override void myMethod(){}
至
public override void myMethod(){}
我收到一個新錯誤,
“找不到合適的方法可以覆蓋。”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Interface
{
interface myInterface
{
void myMethod();
}
class myDerivedClass : myInterface
{
override void myMethod()
{
}
}
class Program
{
static void Main(string[] args)
{
}
}
}
該錯誤有些令人誤解-看起來編譯器首先嘗試在本地對代碼進行推理。 因此,它發現您正在使用private
(默認)說明符進行override
。 顯然這是一個錯誤,但實際上它隱藏了真正的錯誤-開頭沒有任何要覆蓋的內容(您可以看到,如果將代碼更改為public override void myMethod(){}
)。
實際的解決方法是在實現接口方法時將方法public
:
class MyInterfaceImplementationClass : IMyInterface
{
public void MyMethod()
{
}
}
另外,如果您希望直接從類中不可見的方法,您也可以顯式實現該接口(類似於private
,但是可以通過強制轉換為接口來調用):
class MyExplicitInterfaceImplementationClass : IMyInterface
{
void IMyInterface.MyMethod()
{
}
}
interface IMyInterface
{
void MyMethod();
}
我認為您將Interface
與Class
混淆了。
如果要基類派生,請使用class
關鍵字not interface
public class BaseClass
{
public void MyMethod()
{
}
}
public class DerivedClass : BaseClass
{
}
如果您希望能夠override
基類中的方法,則可以將其標記為virtual
並在派生類中使用override
關鍵字。
public class BaseClass
{
public virtual void MyMethod()
{
}
}
public class DerivedClass : BaseClass
{
public override void MyMethod()
{
// do soothing different
base.MyMethod()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.