📜  C#程序检查指定类是否为密封类

📅  最后修改于: 2022-05-13 01:54:41.550000             🧑  作者: Mango

C#程序检查指定类是否为密封类

Sealed 类是不允许用户继承该类的类。我们可以使用密封关键字创建一个密封类。该关键字告诉编译器该类是密封类。在本文中,我们将学习如何检查指定的类是否为密封类。所以我们使用 Type 类的 IsSealed 属性。该属性用于检查给定的 Type 是否是密封的。

句法:

public bool IsSealed { get; }

返回:此属性的返回类型为布尔值。如果给定的类型或类是密封的,它将返回 true,否则,它将返回 false。

示例 1:

C#
// C# program to check if the given 
// class is sealed or not
using System;
using System.Reflection;
  
// Declare a class without sealed
public class Myclass1
{
    public void display()
    {
        Console.WriteLine("Hello! GeeksforGeeks");
    }
}
  
// Declare a class with sealed
sealed class Myclass2 
{
    public void Show()
    {
        Console.WriteLine("Hey! GeeksforGeeks");
    }
}
  
// Driver code
class GFG{
  
public static void Main(string[] args)
{
      
    // Check the given class is sealed or not
    // Using IsSealed property
    Console.WriteLine(typeof(Myclass1).IsSealed);
    Console.WriteLine(typeof(Myclass2).IsSealed);
}
}


C#
// C# program to check if the given 
// class is sealed or not
using System;
using System.Reflection;
  
// Declare a class with sealed keyword
sealed class Myclass 
{
    public void Show()
    {
        Console.WriteLine("Hey! GeeksforGeeks");
    }
}
  
// Driver code
class GFG{
  
public static void Main(string[] args)
{
      
    // Check the given class is sealed or not
    // Using IsSealed property
    if (typeof(Myclass).IsSealed == true)
    {
        Console.WriteLine("The given class is a sealed class");
    }
    else
    {
        Console.WriteLine("The given class is not a sealed class");
    }
}
}


输出:

False
True

示例 2:

C#

// C# program to check if the given 
// class is sealed or not
using System;
using System.Reflection;
  
// Declare a class with sealed keyword
sealed class Myclass 
{
    public void Show()
    {
        Console.WriteLine("Hey! GeeksforGeeks");
    }
}
  
// Driver code
class GFG{
  
public static void Main(string[] args)
{
      
    // Check the given class is sealed or not
    // Using IsSealed property
    if (typeof(Myclass).IsSealed == true)
    {
        Console.WriteLine("The given class is a sealed class");
    }
    else
    {
        Console.WriteLine("The given class is not a sealed class");
    }
}
}

输出:

The given class is a sealed class