简体   繁体   English

我可以将课程内部封闭,但外部密封吗?

[英]Can I make a class unsealed internaly but sealed externaly?

在C#中,是否可以创建一个可以从内部派生(未密封)的类,但是然后阻止其他人在外部引用我的库继承自我的公共类(密封)?

I suppose you could make the constructor of the class internal so that only other classes in your assembly could derive from them, if you still need to create instances of that class you could provide a factory method to return instances. 我想你可以使类的构造函数internal以便只有程序集中的其他类可以从它们派生,如果你仍然需要创建该类的实例,你可以提供一个工厂方法来返回实例。

edit to add a sample: 编辑以添加示例:

public class MyFoo
{
    internal MyFoo()
    {
    }

    public static MyFoo CreateFoo()
    {
        return new MyFoo();
    }
}

Eric Lippert notes three ways to do this. Eric Lippert指出了三种方法。 tl;dr: don't seal your class, but include an internal abstract method in your class, or make all the constructors internal or private, or use the PermissionSet attribute to add metadata to the class. tl; dr:不要密封你的类,但是在你的类中包含一个内部抽象方法,或者使所有构造函数都是内部或私有的,或者使用PermissionSet属性向类中添加元数据。

http://blogs.msdn.com/b/ericlippert/archive/2008/09/26/preventing-third-party-derivation-part-one.aspx http://blogs.msdn.com/b/ericlippert/archive/2008/09/26/preventing-third-party-derivation-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/2008/10/06/preventing-third-party-derivation-part-two.aspx http://blogs.msdn.com/b/ericlippert/archive/2008/10/06/preventing-third-party-derivation-part-two.aspx

You can also try doing something like this. 你也可以尝试做这样的事情。

internal class InternalExtendible
{
    public string MyProperty { get; set; }
}

public sealed class ExternalSealedClass : InternalExtendible
{
}

Create an Internal class and create a public empty class that inherits from the internal class. 创建一个Internal类并创建一个继承自内部类的公共空类。 When referencing the dll, only the public class will be visible to the user, but all the functionality of the internal class will be exposed. 引用dll时,只有公共类对用户可见,但内部类的所有功能都将公开。

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

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