简体   繁体   English

是否可以创建一个只能作为另一个类的成员实例但仍可以通过VB.NET公开访问的类?

[英]Is it possible to create a class that can only be instanced as member of another class, but still be publicly accessible through this in VB.NET?

I have a custom applicationdata class in this I would like to categorize its data through member subclasses eg a userdata class. 我有一个自定义的applicationdata类,我想通过成员子类(例如userdata类)将其数据分类。 However the userdata class should not be able to be instantiated other places than in the applicationdata class, but still be accessible through the applicationdata class. 但是,除了在applicationdata类中之外,不能将userdata类实例化到其他位置,但仍可以通过applicationdata类进行访问。 Is this possible. 这可能吗。

To illustrate I want to be able to access the class like this: ApplicationData.UserData.SomeProperty 为了说明这一点,我希望能够访问此类:ApplicationData.UserData.SomeProperty

However outside the ApplicationData class it should not be possible to instance like this: Dim ud as new UserData 但是,在ApplicationData类之外,不可能像这样进行实例化:将Dim ud作为新的UserData

public class ApplicationData
{
    private UserData user = new UserData();

    public UserData User
    {
        get
        {
            return user;
        }
    }

    public class UserData
    {
        internal UserData()
        {
        }
    }
}

It's not exactly what you describe, in that it's still possible to create a UserData instance outside of your ApplicationData class - but only within the same assembly. 这与您描述的不完全相同,因为仍然可以在ApplicationData类之外创建UserData实例-但只能在同一程序集中。 Note also that you have to name the class (UserData) differently from the property you're exposing (User). 还请注意,您必须为类(UserData)命名,而不是要公开的属性(User)。

Rather than nest the class like this, the approach I would take instead would be to have a public IUserData interface, and an internal UserData class. 与其嵌套这样的类,不如我采用的方法是拥有一个公共的IUserData接口和一个内部的UserData类。 Your ApplicationData class can then expose a UserData property of type IUserData. 然后,您的ApplicationData类可以公开IUserData类型的UserData属性。

我将解决此问题的方法如下:编写公共接口IUserData使UserData实现接口IUserData并将该类设为私有ApplicationData将通过名为IUserData类型的UserData属性公开该类。

You can define user data as a abstract class so that it can only be inherited, can not be instanced. 您可以将用户数据定义为抽象类,以便它只能被继承,不能被实例化。 For more information see this link 有关更多信息,请参见此链接

Now if UserData and ApplicationData reside in the same assembly, you can user 'internal' keyword. 现在,如果UserData和ApplicationData驻留在同一程序集中,则可以使用用户“ internal”关键字。 When you use internal keyword to the class, that class in only accessible in the same assembly. 当您对类使用internal关键字时,该类只能在同一程序集中访问。 The classes which are outside the assembly can not access it. 程序集外部的类无法访问它。 For more information see this link. 有关更多信息,请参见此链接。

Cheerss! 干杯!

Just use an internal constructor. 只需使用内部构造函数即可。

No one outside the assembly will be able to create instances. 程序集外部的任何人都无法创建实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM