您的位置:首页 > 其它

.NET 中的三种接口实现方式

2010-12-17 15:33 417 查看
一般来说.NET提供了三种不同的接口实现方式,分别为隐式接口实现、显式接口实现、混合式接口实现。这三种方式各有各的特点。

首先来看隐式接口实现,这恐怕是我们使用最多的一种接口实现,因为隐匿接口实现是.NET的默认接口实现方式。下面让我们来看一个隐式接口实现的例
子:

using
System;

internal class
MyClass

{

public void
SomeMethod()

{

// 利用接口的方式声明一个Myinplement对象

IMyInterface
iObj = new
MyInplement
();

iObj.MethodA();

// 利用类的方式声明一个Myinplement对象

MyInplement
obj = new
MyInplement
();

obj.MethodB();

}

}

public class
MyInplement
: IMyInterface

{

#region
IMyInterface Members

/// <summary>

///
利用隐式接口实现方式实现接口中的方法

/// </summary>

public void
MethodA()

{

Console
.WriteLine("a"
);

}

/// <summary>

///
利用隐式接口实现方式实现接口中的方法

/// </summary>

public void
MethodB()

{

Console
.WriteLine("B"
);

}

#endregion

}

public interface
IMyInterface

{

void
MethodA();

void
MethodB();

}

上面的代码很简单,我们声明了一个接口,然后利用MyImplement类来实现接口。在实现接口的时候我们选择了隐式接口实现,即在接口中定义的
方法签名前加上修饰符来定义实现方法的签名,比如public void
MethodB()。
这种隐式接口实现用起来很简单,但却有一个缺点,就是它允许客户可以直接调用实现类中的方法,(即通过MyInplement
obj = new
MyInplement
()这样的方式声明对象)而不是通过接口
调用实现类中的方法(即通过的IMyInterface
iObj
= new
MyInplement
();方式来声明对象),这无疑增加了代码的耦合性和违反了面向接口编程的原则。那怎么样
才能禁止客户直接调用实现类呢? 下面我们看的显式接口实现就可以。

显式接口实现是指实现类在实现接口的方法时在方法的签名上用"接口名.方法名”的样式来定义方法名,同时在方法的签名中不允许带有修饰符,因为所有
显式接口实现的方法全是private的,这是.NET为了禁止客户直接调用实现类而硬性规定的。下面我们来看显式接口实现的例子:

using
System;

internal class
MyClass

{

public void
SomeMethod()

{

// 利用接口的方式声明一个Myinplement对象

IMyInterface
iObj = new
MyInplement
();

iObj.MethodA();

// 利用类的方式声明一个Myinplement对象,会报错,因为MyImplement的MethodA方法是private的

MyInplement
obj = new
MyInplement
();

obj.MethodB();

}

}

public class
MyInplement
: IMyInterface

{

#region
IMyInterface Members

/// <summary>

///
利用显式接口实现方式实现接口中的方法

/// </summary>

void
IMyInterface
.MethodA()

{

Console
.WriteLine("a"
);

}

/// <summary>

///
利用显式接口实现方式实现接口中的方法

///
会报错,因为在显式接口实现时不允许带有修饰符

/// </summary>

public  void
IMyInterface
.MethodB()

{

Console
.WriteLine("B"
);

}

#endregion

}

public interface
IMyInterface

{

void
MethodA();

void
MethodB();

}

上面的代码
中有两个地方会报错,这是因为我们在报错的地方违反了显式接口实现的约束。

最后让我们来看混合式接口实现,混合式接口实现就是将隐式接口实现和显式接口实现搭在一起使用,下面让我们来看一个例子:

using
System;

internal class
MyClass

{

public void
SomeMethod()

{

// 利用接口的方式声明一个Myinplement对象

IMyInterface
iObj = new
MyInplement
();

iObj.MethodA();

// 利用类的方式声明一个Myinplement对象,不会报错,因为MyImplement的MethodA方法是public的

MyInplement
obj = new
MyInplement
();

obj.MethodB();

}

}

public class
MyInplement
: IMyInterface

{

#region
IMyInterface Members

/// <summary>

///
利用显式接口实现方式实现接口中的方法

/// </summary>

void
IMyInterface
.MethodA()

{

Console
.WriteLine("a"
);

}

/// <summary>

///
利用隐式接口实现方式实现接口中的方法

/// </summary>

public  void
MethodB()

{

Console
.WriteLine("B"
);

}

#endregion

}

public interface
IMyInterface

{

void
MethodA();

void
MethodB();

}

上面的代码
中我们将MehtodB的实现改为隐式接口实现,这样MyImplement.Method的修饰符就是public的了,代码中就没有错了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: