为什么我们不能在C#中使用IteratorStateMachineAttribute? [英] Why cant we use IteratorStateMachineAttribute in C#?

查看:344
本文介绍了为什么我们不能在C#中使用IteratorStateMachineAttribute?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对试图派生的类进行了转到定义( F12 ),我注意到其中一种方法标记为AsyncStateMachineAttribute.继而继承StateMachineAttribute.我很好奇,决定阅读此属性及其在MSDN上的所有衍生版本.这导致我,我碰到了这个说法:

您不能使用IteratorStateMachineAttribute来测试方法是否是C#中的迭代器方法.

由于该声明很突出,因此必须要有严肃的含义,但是没有进一步的解释.有人在这方面有见识吗?

解决方案

我99%确信它具有历史意义.基本上,C#在C#2中引入了迭代器块-在引入此属性之前很长时间.

等效的async属性是在C#中同时引入异步方法的,所以这很好...但是,即使C#编译器 now IteratorStateMachineAttribute应用于迭代器块:

  • 它不适用于使用较早版本的编译器创建的库,因此您将不能在那里依赖它.
  • 它不适用于以.NET之前的版本为4.5的库. (说实话,我不确定VB编译器在做什么.它可能会忽略该属性,或者可能要求您将.NET定位为最新版本才能使用迭代器方法.)

我想说,方法上存在IteratorStateMachineAttribute可以很好地表明它迭代器方法(尽管没有什么可以阻止顽皮的开发人员将其应用于其他方法的),但是由于C#编译器的版本较旧,这还不够充分.

I did a Go To Definition (F12) on a class I was trying to derive from and I noticed that one of the methods was marked with AsyncStateMachineAttribute. Which in turn inherits StateMachineAttribute. I was curious and decide to read up on this attribute and all its derivates on MSDN. That led me to this and I came across this statement:

You can't use IteratorStateMachineAttribute to test whether a method is an iterator method in C#.

Because that statement is made to stand out, there must be serious implications to it but there is no further explanation as to why that is so. Does anyone have insights in this regard?

解决方案

I'm 99% sure it's historical. Basically, C# introduced iterator blocks in C# 2 - a long time before this attribute was introduced.

The equivalent async attribute was introduced at the same time as async methods in C#, so that was fine... but even though the C# compiler now applies IteratorStateMachineAttribute to iterator blocks:

  • It doesn't apply to libraries created with older versions of the compiler, so you wouldn't be able to rely on it there.
  • It can't apply to libraries targeting versions of .NET prior to 4.5. (I'm not sure what the VB compiler does here, to be honest. It may omit the attribute, or it may require you to be targeting a recent version of .NET in order to use iterator methods.)

I would say that the presence of an IteratorStateMachineAttribute on a method is a good indicator that it is an iterator method (although there's nothing to stop a mischievous developer applying it to other methods), but it's not a sufficient test due to older versions of the C# compiler.

这篇关于为什么我们不能在C#中使用IteratorStateMachineAttribute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆