簡體   English   中英

為什么我不能在 C# 中將匿名類型作為泛型返回,而我可以對方法參數執行相同的操作?

[英]why I can't return anonymous type as generic in C#, while I can do the same for method parameters?

考慮這段代碼:

using System;

class EntryPoint{

    static void Main(){
        f(new{ Name = "amir", Age = 24 });
    }

    static void f <T> (T arg){}

}

此代碼使用 C# 9 編譯器編譯。 我可以在需要泛型類型的地方發送匿名類型。 我的問題是為什么我不能對方法返回類型做同樣的事情?

例如,考慮以下代碼:

using System;

class EntryPoint{

    static void Main(){
        object obj = f();
    }

    static T f <T> (){
        return new{ Name = "amir", Age = 24 };
    }

}

它將得到以下編譯錯誤:

main.cs(6,22):錯誤 CS0411:無法從用法中推斷方法“EntryPoint.f()”的類型 arguments。 嘗試明確指定類型 arguments。

main.cs(10,16):錯誤 CS0029:無法將類型“<匿名類型:字符串名稱,int Age>”隱式轉換為“T”

為什么這些相同的錯誤不會出現在其他代碼中。 在其他代碼中,匿名類型也隱式轉換為 T。為什么這不能在這里發生?

提前感謝您幫助我!

匿名類型只是 C# 編譯器為您定義的類型。 因此,讓我們更改您的示例以使用具體類型;

public class Foo {
    public string Name { get; set; }
    public int Age { get; set; }
}

static void Main(){
    f1(new Foo{ Name = "amir", Age = 24 });
}

static void f1<T> (T arg){}

static T f2<T> (){
    return new Foo{ Name = "amir", Age = 24 };
}

現在在第二個例子中應該很明顯,類型TFoo是不一樣的。

暫無
暫無

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

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