C# 在声明(.NET)中强制使用接口而不是具体实现 在C++中,可以做到以下几点: class base_class { public: virtual void do_something() = 0; }; class derived_class : public base_class { private: virtual void do_something() { std::cout << "do_something() called"; } };
如果将对象声明为类型C# 在声明(.NET)中强制使用接口而不是具体实现 在C++中,可以做到以下几点: class base_class { public: virtual void do_something() = 0; }; class derived_class : public base_class { private: virtual void do_something() { std::cout << "do_something() called"; } };,c#,.net,c++,inheritance,access-modifiers,C#,.net,C++,Inheritance,Access Modifiers,如果将对象声明为类型派生类,则无法调用该方法,因为它是私有的: derived_class *object = new derived_class(); object->do_something(); // --> error C2248: '::derived_class::do_something' : cannot access private member declared in class '::derived_class' 我认为这很好,因为如果创建一个用作接口的
派生类
,则无法调用该方法,因为它是私有的:
derived_class *object = new derived_class();
object->do_something();
// --> error C2248: '::derived_class::do_something' : cannot access private member declared in class '::derived_class'
我认为这很好,因为如果创建一个用作接口的抽象类,可以确保没有人意外地将字段声明为具体类型,而是始终使用接口类
由于在C#/.NET中,一般情况下,重写方法时不允许将访问权限从public
缩小到private
,这里有没有实现类似效果的方法 您可以通过将方法标记为new
来降低其可用性
示例来自:
作为一项学术活动,这确实更有趣;如果您的代码确实依赖于不能在
ADerivedType
上调用BasePublicMethod
,这是一个可疑设计的警告信号。您也可以在.Net世界中使用
例如,实现,但您必须将其强制转换到
IBindingList
才能查看该方法。如果实现该策略,则该策略的问题在于该方法不是真正私有的。如果要向上转换对base\u class
的引用,则该方法现在是公共的。由于它是一个虚拟方法,用户代码将执行派生类::do\u something()
即使它被标记为私有。如果显式实现接口,这至少会鼓励人们在声明中使用接口类型
interface IMyInterface
{
void MyMethod();
}
class MyImplementation : IMyInterface
{
void IMyInterface.MyMethod()
{
}
}
只有将实例强制转换为IMyInterface
后,才能看到MyMethod。如果声明使用接口类型,则在后续使用中不需要强制转换
(谢谢卢克,节省了我几秒钟^)
在这个场景中,这并不是一个bug,而是一个特性。它被称为显式接口实现:@Luke谢谢你的链接,我一直在努力找到它:)
using System;
namespace UsageLibrary
{
public class ABaseType
{
public void BasePublicMethod(int argument1) {}
}
public class ADerivedType:ABaseType
{
// Violates rule: DoNotDecreaseInheritedMemberVisibility.
// The compiler returns an error if this is overridden instead of new.
private new void BasePublicMethod(int argument1){}
}
}
interface IMyInterface
{
void MyMethod();
}
class MyImplementation : IMyInterface
{
void IMyInterface.MyMethod()
{
}
}
IMyInterface instance = new MyImplementation();
instance.MyMethod();
MyImplementation instance2 = new MyImplementation();
instance2.MyMethod(); // Won't compile with an explicit implementation
((IMyInterface)instance2).MyMethod();