Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何正确地公开DLL的函数?_C#_Api_Oop_Dll_Interface - Fatal编程技术网

C# 如何正确地公开DLL的函数?

C# 如何正确地公开DLL的函数?,c#,api,oop,dll,interface,C#,Api,Oop,Dll,Interface,我目前正在编写一个DLL文件,它使用了一些继承。现在我在公开我的类时遇到了麻烦,因为所有的基类都是公开的 例如: public Class TestBase // Base class that gets exposed { } public Class TestFunctions : TestBase // The class that I want to expose gets exposed { } 内部或其他修改器问题(如受保护): 我想向DLL文件的用户公开TestFunctions

我目前正在编写一个DLL文件,它使用了一些继承。现在我在公开我的类时遇到了麻烦,因为所有的基类都是公开的

例如:

public Class TestBase // Base class that gets exposed
{
}
public Class TestFunctions : TestBase // The class that I want to expose gets exposed
{
}
内部或其他修改器问题(如受保护):


我想向DLL文件的用户公开
TestFunctions
,但我不想公开
TestBase
,因为基类只在内部使用。对于DLL的用户来说,公开基类是多余的,因为他所需要的一切都包含在一个函数类中。我如何实现我所需要的?我听说界面可以帮我解决问题,但我无法确定我到底需要做什么,因为用户无法实例化实例。

您可以使用工厂方法和界面:

例如:

//your classes: internal
internal class TestBase // Base class that I dont want to expose
{

}

//note: added interface
//note2: this class is not exposed
internal class TestFunctions : TestBase, IYourTestClass // The class that I want to expose
{

}

//an interface to communicate with the outside world:
public interface IYourTestClass
{
    //bool Test();  some functions and properties
}

//and a public factory method (this is the most simple version)
public static class TestClassesFactory
{
    public static IYourTestClass GetTestClass()
    {
        return new TestFunctions();
    }
}
因此,在调用者的应用程序中,现在两个类都没有公开。相反,您可以使用工厂申请新工厂:

public void Main()
{
    IYourTestClass jeuh = TestClassesFactory.GetTestClass();
}

为什么不想公开基类?这个答案可能有助于其他人理解接口和/或抽象类是否有帮助。@NisargShah我编辑了我的问题您可以通过
private
(仅从同一类可用)、
internal
(向同一程序集中的所有成员公开)或
protected
来封装您需要的所有成员(仅对派生类型公开) modifiers@Fabjan不,这不起作用。我使用的是继承,这意味着所有基类都必须具有与我要公开的类相同的修饰符。如果我对基类使用'internal'或'protected',我要公开的类也是隐藏的。@Anon请提供一个看起来很有希望的,我会尝试一下。非常感谢!这是吗所谓的“工厂模式”然后?另一个注意事项:这是最简单的工厂类型:通常有更多与
IYourTestClass
相关的类型,工厂实际上可以选择返回哪个类型。例如:一个方法说:给我需要返回的对象的实例?@Anon:我错了:“工厂”之间的区别,“工厂方法”和“抽象工厂”可以在这里找到。但是,它应该可以工作。是的,工厂就是这样做的。尽管在实践中,它更像是:给我一个具有此接口的对象的实例。你可以隐藏1)实现细节和2)创建参数。通常与控制反转一起使用,例如在.net Core中,您可以从框架中请求服务。代码项目文章:
public void Main()
{
    IYourTestClass jeuh = TestClassesFactory.GetTestClass();
}