如何创建公共接口的实例 [英] How do I create an instance of a public interface

查看:102
本文介绍了如何创建公共接口的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个代码示例:我不想公开内部密封类只是界面。



这里是我想要做的事IDataService id =新的IDataService()是可能还是有解决方法?



  public   interface  IDataService 
{
方法a
方法b
方法c
方法等
}

内部 密封 DataService:IDataService
{
方法a
方法b
方法c
方法等$
}



谢谢



我尝试了什么:



我唯一尝试过的方法就是改变该类是公开的,但这不是我的选择

解决方案

无法从界面创建对象!

我我不确定你不暴露课程是什么意思,但你唯一的选择是:

 IDataService id =  new  DataService()


你不能创建一个接口的实例。

你定义一个实现接口的类。然后创建该类的实例。



 //这可以
IDataService myService = new DataService();


您必须遵守以下规则:接口(C#编程指南)| Microsoft Docs [ ^ ],

特别是:

引用:

要实现一个接口成员,相应的实现成员class必须是公共的,非静态的,并且与接口成员具有相同的名称和签名。


Here is a code sample: I don't want to expose the internal sealed class just the interface.

here is what I want to do IDataService id = new IDataService() is it possible or is there a work around?

public interface IDataService
{
    method a
    method b
    method c
    method etc
}

internal sealed class DataService : IDataService
{
    method a
    method b
    method c
    method etc
}


thanks

What I have tried:

The only thing I have tried that works is to change the class to public but that is not an option for me

解决方案

There is no way to create an object from an interface!
I'm not sure what do you mean by not exposing the class, but your only option is:

IDataService id = new DataService()


You can't create an instance of an interface.
You define a class which implements the interface. Then create an instance of that class.

// This works
IDataService myService = new DataService();


You have to follow the rules: Interfaces (C# Programming Guide) | Microsoft Docs[^],
Especially:

Quote:

To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.


这篇关于如何创建公共接口的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆