[英]Why the type is System.Object here?
Here is some piece of code : 这是一段代码:
Func<dynamic> f1 = new Func<dynamic>(() => 10);
Func<int> f2 = () => 10;
Console.Write(f1.Method.ReturnType);
Console.Write(" and " + f2.Method.ReturnType );
Output : System.Object and System.Int32
输出: System.Object and System.Int32
My question is : 我的问题是:
Why dynamic
type inferred by DLR (type that is used for dynamic
) here is System.Object
and is not System.Int32
? 为什么要dynamic
的DLR推断类型(类型用于dynamic
)这里是System.Object
,而不是System.Int32
? It's not very logical as it also involves boxing of the Int32 struct to object. 这不是很合乎逻辑,因为它还涉及将Int32结构装箱到对象。
As far as i understand, when we check type here we do it dynamically on execution time because we use Reflection. 据我所知,当我们在这里检查类型时,我们会在执行时动态执行,因为我们使用Reflection。 So it's known to DLR by then that it's int
but for some reason it boxes it into Object
... Why? 所以当时DLR知道它是int
但是由于某种原因它将它装入Object
...为什么?
I've tried to find anything regarding this on SO and googled for it but I couldn't find any answer that explains it all. 我试图在SO上找到任何关于它的东西并用Google搜索,但我找不到任何解释这一切的答案。
Nothing is inferred here. 这里没有任何推断。 It just doesn't know the type until it executes, and that is why the type given is object
. 它只是在执行之前不知道类型,这就是给定类型是object
。 The ( static ) compiler doesn't know the type since you don't know it yet. ( 静态 )编译器不知道类型,因为您还不知道它。 It is passed around as object
and on the calling side it is dynamic
again. 它作为object
传递,并且在调用方面它再次是dynamic
。
This is the same for regular methods: 对于常规方法,这是相同的:
Console.Write(typeof(Program).GetMethod("F1").ReturnType);
public static dynamic F1()
{
return 10;
}
Output: 输出:
System.Object System.Object的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.