C#--接口的实现

时间:2024-05-13 16:35:08

接口:

    1. 不允许使用访问修饰符,所有接口成员都是公共的.
    2. 接口成员不能包含代码体.
    3. 接口不能定义字段成员.
    4. 接口成员不能使用关键字static,vritual,abstract,sealed来定义.
    5. 类型定义成员是禁止的.

如果要隐藏继承了接口中的成员,可以用关键字new来定义它们.

public interface IMyInterface
{
void DoSomething();
} public interface IMyDeInterface : IMyInterface
{
new void DoSomething();
}

在接口中定义的属性可以确认访问块get和set中的哪一个能用于该属性.

public interface IMyInterface
{
int myNum
{
get;
set;
}
}

注意:接口中不能指定字段.

在类中实现接口:

当一个类实现一个接口时,可以使用abstract或virtual来执行接口的成员,而不能使用static或const.

一个类的如果实现了一个借口,那么这个类的派生类隐式的支持该接口.

显式执行接口成员

接口成员可以由类显式的执行.如果这么做,那么这个成员只能通过接口来访问.而不能通过类来访问.

public interface IMyInterface
{
void DoSomeThing();
} public class MyClass : IMyInterface
{
void IMyInterface.DoSomeThing()
{
throw new NotImplementedException();
}
}
 
    protected void Page_Load(object sender, EventArgs e)
{
//此时mc是没有方法的.
MyClass mc = new MyClass(); //此时my有个方法DoSomeThing()
IMyInterface my = mc;
my.DoSomeThing();
}
 
隐式执行接口成员
默认都是隐式执行接口成员.
public interface IMyInterface
{
void DoSomeThing();
} public class MyClass : IMyInterface
{
public void DoSomeThing()
{
throw new NotImplementedException();
}
}
 
    protected void Page_Load(object sender, EventArgs e)
{
MyClass mc = new MyClass();
mc.DoSomeThing();
}

类实现接口属性

public interface IMyInterface
{
int MyNum
{
get;
}
} public class MyClass : IMyInterface
{
protected int myNum;
public int MyNum
{
get
{
return myNum;
}
set
{
myNum = value;
}
}
}
 
    protected void Page_Load(object sender, EventArgs e)
{
MyClass mc = new MyClass();
mc.MyNum = 12;
}