📜  C# 程序检查指定类型是否为接口

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

C# 程序检查指定类型是否为接口

接口就像一个类,它也可以有方法、属性、事件等作为它的成员,但它只包含成员的声明,这些成员的实现将由隐式实现接口的类给出或明确。我们可以使用 Type 类的 IsInterface 属性来检查指定的类型是否为接口。如果给定类型是接口,它将返回 true。否则,它将返回 false。它是一个只读属性。

语法

public bool IsInterface { get; }

示例 1:

C#
// C# program to check whether the 
// given type is interface or not
using System;
using System.Reflection;
  
// Declare an interface
interface myinterface
{
      
    // Method in interface
    void gfg();
}
  
class GFG{
      
// Driver code
static void Main()
{
      
    // Check the type is interface or not
    // Using the IsInterface property
    if (typeof(myinterface).IsInterface == true) 
    {
        Console.WriteLine("Yes it is Interface");
    }
    else 
    {
        Console.WriteLine("No it is not an Interface");
    }
}
}


C#
// C# program to check whether the 
// given type is interface or not
using System;
using System.Reflection;
  
// Declare an interface
interface myinterface
{
      
    // Method in interface
    void gfg();
}
  
// Declare a class
public class myclass
{
    public void myfunc(){}
}
  
// Declare a struct
public struct mystruct
{
    int a;
}
  
class GFG{
      
// Driver code
static void Main()
{
      
    // Check the type is interface or not
    // Using the IsInterface property
    Console.WriteLine(typeof(myinterface).IsInterface);
    Console.WriteLine(typeof(myclass).IsInterface);
    Console.WriteLine(typeof(mystruct).IsInterface);
}
}


输出:

Yes it is Interface

示例 2:

C#

// C# program to check whether the 
// given type is interface or not
using System;
using System.Reflection;
  
// Declare an interface
interface myinterface
{
      
    // Method in interface
    void gfg();
}
  
// Declare a class
public class myclass
{
    public void myfunc(){}
}
  
// Declare a struct
public struct mystruct
{
    int a;
}
  
class GFG{
      
// Driver code
static void Main()
{
      
    // Check the type is interface or not
    // Using the IsInterface property
    Console.WriteLine(typeof(myinterface).IsInterface);
    Console.WriteLine(typeof(myclass).IsInterface);
    Console.WriteLine(typeof(mystruct).IsInterface);
}
}

输出:

True
False
False