【问题标题】:IEnumerable doest not contain a definition for 'Length'IEnumerable 不包含“长度”的定义
【发布时间】:2018-11-06 19:56:06
【问题描述】:
 error CS1061: 'IEnumerable<Attribute>' does not contain a definition for 'Length' and no extension method 'Length' accepting a first argument of type 'IEnumerable<Attribute>' could be found (are you missing a using directive or an assembly reference?)

当我尝试使用 .Net 而不是 IL2CPP 进行编译时,使用 Unity 2018 时出现此错误 这是我得到错误的行:

 if (methods[i].GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Length != 0)
            {
                continue;
            }

而且,在这个其他方法中:

  var ret = (Delegate.CreateDelegate(typeof(V), target, method) as V);

另外,在这个方法中,我使用了 methodinfo 而不是 Delegate。但随后询问没有使用 3 个值的方法。

还添加了“使用 system.Linq”

最好的问候

【问题讨论】:

  • 你的问题是什么?
  • .Count().Any() 可能是您想要的。
  • .Count() 而不是 Length;或(更好).Any() - 如果IEnumerable&lt;T&gt; 中有任何项目
  • 这是因为IEnumerable 不是任何长度。它只是一个方法GetEnumerator() 的接口。通常会混淆IEnumerable 是具有固定长度的某种类型的数组,但这不一定是而且通常不是这样。 ArrayList 确实使用 IEnumerable 接口,但接口本身并不意味着存在任何项目。

标签: c#


【解决方案1】:

实际上你想测试 any 项是否在IEnumerable&lt;T&gt;

 if (methods[i].GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Any())
 {
     continue;
 }

如果你坚持Length != 0 方法正确的语法是

 if (methods[i].GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Count() > 0)
 {
     continue;
 }

【讨论】:

  • @Rahul:谢谢!从技术上讲,!= 0&gt; 0 在上下文中是相等的;但&gt; 0 更具可读性。
  • 推荐第一个.Any(),因为只要结果是true,它就会返回true;在这种情况下,这将是任何第一次迭代。 Count() 将枚举整体并返回一个值来比较慢得多。
  • 值得注意的是,一些枚举甚至不包含对象,而是在枚举上创建它们,这会使CountAny 都变慢但Count 慢得多。
【解决方案2】:

好的,现在这工作正常:

 if (methods[i].GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Count() > 0)

现在,另一个错误:

var ret = (Delegate.CreateDelegate(typeof(V), target, method) as V);

我尝试使用 MethodInfo,但无法正常工作。 “Delegate”不包含“CreateDelegate”的定义

【讨论】:

  • 这是一个完全不同的问题@pacogp - 请写一个新问题而不是在这里讨论它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 1970-01-01
  • 2019-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-20
相关资源
最近更新 更多