Interface - I1 (contains M1 method) Class - C1:I1 (c1 implements I1) Class - C2:C1 (C2 inherits C1)
interface I1
{
void M1();
}
class C1 : I1
{
void M1(){}
}
class C2 : C1
{
}
Requirement: There should not be any implementation of "M1" in "C1" , basically "M1" needs to be implemented in "C2"
How to achieve this using any of the OOPs concepts?
As long as you can tolerate C1 being abstract, this works:
interface I1
{
void M1();
}
abstract class C1 : I1
{
public abstract void M1();
}
class C2 : C1
{
public override void M1()
{
//
}
}
Edit : As Isantipov noted in the comment you can avoid the abstract class like this:
class C1 : I1
{
public virtual void M1()
{
throw new NotSupportedException();
}
}
使C1
抽象化并将M1
定义为抽象方法。
You are looking for abstract method [wiki] :
An abstract method is one with only a signature and no implementation body. It is often used to specify that a subclass must provide an implementation of the method. Abstract methods are used to specify interfaces in some computer languages.
An abstract method declaration introduces a new virtual method but does not provide an implementation of that method. Instead, non-abstract derived classes are required to provide their own implementation by overriding that method. Because an abstract method provides no actual implementation, the method-body of an abstract method simply consists of a semicolon.
In your case:
interface I1
{
void M1();
}
abstract class C1 : I1
{
public abstract void M1();
}
class C2 : C1
{
public override void M1()
{
// Your code here
}
}
You can either make C1 abstract or you can use Explicit implementation. This means it is implemented, but it is not visible.
class C1 : I1
{
void I1.M1(){ throw new NotImplementedException(); }
}
It is invalid to call it like this:
C1 c1 = new C1();
c1.M1(); //Error
An alternative answer.
You could have multiple interfaces. .NET Fiddle
interface I1
{
void someCommonMethod();
}
interface I2
{
void M1();
}
Then your classes can inherit like this.
class C1 : I1
{
public void someCommonMethod()
{
...
}
}
class C2 : C1, I2
{
public void M1()
{
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.