开发者

Can I make a class unsealed internally but sealed externally?

开发者 https://www.devze.com 2023-01-23 20:13 出处:网络
In C# is it possible to make a class that can be derived from internally (开发者_JAVA百科unsealed), but then prevent other people referencing my library externally from inheriting from my public class

In C# is it possible to make a class that can be derived from internally (开发者_JAVA百科unsealed), but then prevent other people referencing my library externally from inheriting from my public class (sealed)?


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.

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. 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.

  • https://web.archive.org/web/20150905101050/http://blogs.msdn.com/b/ericlippert/archive/2008/09/26/preventing-third-party-derivation-part-one.aspx
  • https://web.archive.org/web/20151029232826/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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消