簡體   English   中英

如何判斷方法返回哪個接口

[英]How to tell which interface is returned by a method

鑒於此代碼段可以輕松粘貼到Linqpad中(或在Visual Studio控制台解決方案中稍作修改):

void Main()
{
    var cat = this.GetCat();
    var dog = this.GetDog();
    cat.Think();
    cat.ThinkHarder();
    //dog.Think(); // Does not compile.
    //dog.ThinkHarder(); // Does not compile.

    //if ([dog is returned as ISmartAnimal]) // What to put here?
        ((ISmartAnimal)dog).Think(); // Compiles, runs, but shouldn't.

    reportTypeProperties(cat);
    reportTypeProperties(dog);
}

interface IAnimal
{
    string Name { get; set; }
}

interface ISmartAnimal : IAnimal
{
    void Think();
}

class Animal : IAnimal, ISmartAnimal
{
    public string Name { get; set; }
    public void Think() { }
}

ISmartAnimal GetCat()
{
    return new Animal();
}

IAnimal GetDog()
{
    return new Animal();
}

static void reportTypeProperties(object obj)
{
    var type = obj.GetType();
    Console.WriteLine("Type: {0}", type.Name);
    Console.WriteLine("Is smart? {0}", obj is ISmartAnimal);
}

static class ext
{
    public static void ThinkHarder(this ISmartAnimal animal)
    { }
}

reportTypeProperties的輸出顯示dog雖然作為IAnimal返回,但“is”是一個ISmartAnimal。 (兩個對象相同)

類型:動物
聰明嗎? 真正

這是因為GetType()返回對象的具體類型,而不是其當前接口。

我的問題。 有沒有辦法告訴dog被歸還為IAnimal? (見偽代碼)。 編譯器知道(quickview也是如此)。 假設我有一些動物對象,我想在運行時代碼中檢查是否可以使它成為Think()

背景:
這似乎是一項學術活動。 讓一個類(Animal)實現一個你不想總是暴露的接口(ISmartAnimal)似乎很奇怪。 但我問,因為我在Entity Framework中遇到過類似的東西。 如果您需要,可以在此處閱讀,但它會轉向EF特定功能。 如果您不想深入研究,那么就足以說Animal必須實現這兩個接口。


免責聲明:
“任何與真實動物的相似之處純屬巧合:)”

聽起來你dog變量編譯時類型感興趣。 你可以排序得到這個,通過使ReportTypeProperties通用的,讓編譯器推斷基於變量的類型類型:

static void ReportTypeProperties<T>(T obj)
{
    Console.WriteLine("Compile-time type: {0}", typeof(T).Name);
    Console.WriteLine("Actual type: {0}", obj.GetType().Name);
    Console.WriteLine("Is smart? {0}", obj is ISmartAnimal);
}

請注意,這可以通過各種方式進行游戲,例如

object dog = GetDog();
ReportTypeProperties(dog); // Would show as object

要么

IAnimal dog = GetDog();
ReportTypeProperties<object>(dog); // Would show as object

現在還不是很清楚這里的大局是什么 - 我不太可能朝着這個方向前進,這將導致一個好的設計。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM