溫馨提示×

c# typeof能用于接口實現嗎

c#
小樊
102
2024-11-16 21:46:51
欄目: 編程語言

在C#中,typeof關鍵字主要用于獲取一個類型的類型信息。它不能直接用于接口實現,但是你可以使用typeof來獲取接口類型的類型信息,然后使用這個信息來處理實現了該接口的對象。

例如,假設你有一個接口IMyInterface和一個實現了該接口的類MyClass

public interface IMyInterface
{
    void MyMethod();
}

public class MyClass : IMyInterface
{
    public void MyMethod()
    {
        Console.WriteLine("MyMethod called.");
    }
}

要檢查一個對象是否實現了IMyInterface接口,你可以使用is關鍵字:

object obj = new MyClass();

if (obj is IMyInterface)
{
    IMyInterface myInterface = (IMyInterface)obj;
    myInterface.MyMethod();
}
else
{
    Console.WriteLine("Object does not implement IMyInterface.");
}

如果你想要使用typeof來獲取接口類型的類型信息,可以這樣做:

Type interfaceType = typeof(IMyInterface);
Console.WriteLine($"The type of IMyInterface is: {interfaceType}");

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女