简体   繁体   中英

'string[]' does not contain a definition for 'Cast'

I am getting the error:

'string[]' does not contain a definition for 'Cast' and no extension method 'Cast' accepting a first argument of type 'string[]' could be found (are you missing a using directive or an assembly reference?)

on the following piece of code:

return mNames.Cast().ToArray();

What using directive or assembly reference do I need? How do I find out such things?

I'm a noob at C# and .NET, I'm just copying code to get a job done, so don't get too technical with me.

(1) Make sure you are working on C# 3.0+

(2) Make sure your code contains:

using System.Linq;

(3) .Cast is a generic method, you need to specify the type parameter, like this:

return mNames.Cast<AnotherType>().ToArray();

That usually happens when you're missing using System.Linq; at the top of your file.

You'll also need to be using .NET 3.5 or greater for it to work. System.Linq is in the assembly System.Core.dll, which is included by default in projects that use .NET 3.5 or higher.

EDIT

On closer inspection, that code will never work as written, because the Enumerable.Cast() method is generic, and requires you to pass in the type that you are casting to: eg mNames.Cast<object>().ToArray();

Usually, you call the Cast<T>() extension method with a type argument, like mNames.Cast<SomeType>() .

Anyway, mNames already seems to be a string[] , so what do you want to cast it to? Casting to object wouldn't be necessary, because object[] can be assigned from string[] .

即使您没有明确使用“Cast”,如果您使用Linq表达式并忘记“使用System.Linq;”,也会出现此编译错误。

使用primary.AddRange(secondary);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM