dynamic(翻译)
So I asked this guy, what's up with the dynamic keyword, and what type was it exactly? I mean, C# isn't dynamic, right? He says:
我问这个伙计,这dynamic关键字,是什么呢,它是什么类型呢?因为 我认为,c#不是动态类型,他应该有明确的意思和类型,我说的不对吗,但他说:
"Oh, well it's statically-typed as a dynamic type."
它是静态类型作为动态类型。
Then my brain exploded and began to leak out my ears. Honestly, though, it took a second. Here's a good example from some of Ander's slides:
我的思想开始爆发,实际上,这花费了我一些时间。这里是一个好的例子
Calculator calc = GetCalculator();
int
sum = calc.Add(10, 20);
That's the creation of an object, invokation of a method, and the collection of a return value. This is the exact same code, as the "var" type is figured out at compile time.
创建一个对象,然后这个对象的方法,并获得方法的返回值。下面是一个同样的代码,但是稍微不同的是,用到了var(var定义的对象,必须在编译时能获得它的明确引用)
var calc = GetCalculator();
int
sum = calc.Add(10, 20);
If you wanted to do the exact same thing, except with Reflection (like if it were some other class, maybe old-COM interop, or something where the compiler didn't know a priori that Add() was available, etc) you'd do this:
如果上面的对象不能在编译时指明的话,只能用反射(例如,一些其它的类,可能是old-com interop,或者其它的一些东西,导致编译器不能预先知道这个add方法,是有效的)
object
calc = GetCalculator();
Type calcType = calc.GetType();
object
res = calcType.InvokeMember(
"Add"
,
BindingFlags.InvokeMethod,
null
,
new
object
[] { 10, 20 });
int
sum = Convert.ToInt32(res);
It's pretty horrible to look at, of course. If the object is some dynamic thing (from any number of sources), we can do this:
上面那段代码是多么的槽糕,如果一些东西是动态的,我们就可以做成下面这个样子的
dynamic calc = GetCalculator();
int
sum = calc.Add(10, 20);
I'm told this is a dynamic expression that will be resolved at runtime.
Here's a C# program calling a method in a python (.py) file:
1
2
3
4
5
6
7 |
ScriptRuntime py = Python.CreateRuntime(); dynamic random = py.UseFile( "random.py" ); //Make an array of numbers var items = Enumerable.Range(1, 7).ToArray(); random.shuffle(items); |
原文链接:http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx