我正在查看一些C#代码,以获得VS2010中的扩展语言支持(书籍示例)。我看到了一些名为internal sealed class
这些是做什么的?会使用它们吗?
答案 0 :(得分:138)
答案 1 :(得分:15)
答案 2 :(得分:11)
答案 3 :(得分:5)
答案 4 :(得分:4)
答案 5 :(得分:2)
内部
内部类型或成员只能在同一程序集中的文件中访问。
示例
// Assembly1.cs
// Compile with: /target:library
internal class BaseClass
{
public static int intM = 0;
}
// Assembly1_a.cs
// Compile with: /reference:Assembly1.dll
class TestAccess
{
static void Main()
{
var myBase = new BaseClass(); // compile error
}
}
密封
首先,让我们从定义开始。密封是一个修饰符,如果将其应用于类将使其不可继承,并且如果将其应用于虚拟方法或属性则将使其不可验证。
public sealed class A { ... }
public class B
{
...
public sealed string Property { get; set; }
public sealed void Method() { ... }
}
其用法的一个例子是专门的类/方法或属性,其中潜在的更改可能会使它们停止按预期方式工作(例如,System.Drawing命名空间的Pens类)。
...
namespace System.Drawing
{
//
// Summary:
// Pens for all the standard colors. This class cannot be inherited.
public sealed class Pens
{
public static Pen Transparent { get; }
public static Pen Orchid { get; }
public static Pen OrangeRed { get; }
...
}
}
因为不能继承密封类,所以不能将其用作基类,因此,抽象类不能使用密封修饰符。同样重要的是要提到结构是隐式密封的。
示例
public class BaseClass {
public virtual string ShowMessage()
{
return "Hello world";
}
public virtual int MathematicalOperation(int x, int y)
{
return x + y;
}
}
public class DerivedClass : BaseClass {
public override int MathematicalOperation(int x, int y)
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior
return x - y;
}
public override sealed string ShowMessage()
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior but because it's sealed prevent classes that derive from it to override the method
return "Hello world sealed";
}
}
public class DerivedDerivedClass : DerivedClass
{
public override int MathematicalOperation(int x, int y)
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior
return x * y;
}
public override string ShowMessage() { ... } // compile error
}
public sealed class SealedClass: BaseClass {
public override int MathematicalOperation(int x, int y)
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior
return x * y;
}
public override string ShowMessage()
{
// since BaseClass has a method marked as virtual, DerivedClass can override it's behavior but because it's sealed prevent classes that derive from it to override the method
return "Hello world";
}
}
public class DerivedSealedClass : SealedClass
{
// compile error
}
Microsoft文档