[英]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 };
}
现在在第二个例子中应该很明显,类型T
和Foo
是不一样的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.