I’m new to C# programming and have hit a snag I cannot get past.
I’m getting this compile error:
CS0305: Using the generic type ‘System.Collections.Generic.IEnumerable’ reuires 1 type arguments
with this code;
class Program
{
static void Main(string[] args)
{
Car c = new Car();
c.PetName = "Frank";
c.Speed = 55;
c.colour = "Green";
Console.WriteLine("Name = : {0}", c.PetName);
c.DisplayStats();
Garage carLot = new Garage();
// Hand over each car in the collection
foreach (Car c in carLot)
{
Console.WriteLine("{0} is going {1} MPH",
c.PetName, c.CurrentSpeed);
}
Console.ReadLine();
}
class Car
{
//Automatic Properties
public string PetName { get; set; }
public int Speed { get; set; }
public string colour { get; set; }
public void DisplayStats()
{
Console.WriteLine("Car Name: {0}", PetName);
Console.WriteLine("Speed: {0}", Speed);
Console.WriteLine("Color: {0}", colour);
}
}
public class Garage
{
private Car[] CarArray = new Car[4];
// Fill with some car objects on startup.
public Garage()
{
carArray[0] = new Car("Rusty", 30);
carArray[1] = new Car("Clunker", 55);
carArray[2] = new Car("Zippy", 30);
carArray[3] = new Car("Fred", 30);
}
}
public IEnumerator GetEnumerator()
{
foreach (Car c in carArray)
{
yield return c;
}
}
}
How can I resolve this?
asked May 1, 2011 at 3:32
3
There are two variants of IEnumerable
, the generic one (which is in the System.Collections.Generic
namespace) accepts a type argument which specified the types of objects that the enumerable contains. The other one (contained in the System.Collections
namespace) has no type argument and so exposes the type object
— you appear to be declaring / using the non-generic variant, however are not using the System.Collections
namespace.
I think the quick way to fix your particular compile error is to put the following at the top of your source code file:
using System.Collections;
Alternatively you can instead use the Generic version (which you should try to do wherever possible as it is type safe) by specifying type parameters when you declare IEnumerable
, like this:
IEnumerable<Car>
IEnumerator<Car>
You might also want to read An Introduction to C# Generics
You also seem to have a few more errors than that, but these seem like they might be from problems copying and pasting the source (specifically Garage
does not implement IEnumerable
, either the generic or non-generic version, and GetEnumerator
is on the Program
class, not the Garage
class).
answered May 1, 2011 at 3:39
JustinJustin
83.8k48 gold badges221 silver badges360 bronze badges
0
You have more errors than just that. But specifically for that error, you’re looping over Garage
in a foreach
, but that class does not expose an enumerator, mainly because the method GetEnumerator
is actually outside of the class. Move the method inside Garage
and then you’ll be able to get all the way to scene of the next crash.
Actually, for that error, you need using System.Collections;
and then you need to move the GetEnumerator
method. Like I said, you have tons of errors in this code.
2
You have a lot of typos. As others have said, your specific answer is you need to add «: IEnumerable» to your class Garage statement.
Here is the code fixed enough to compile cleanly:
class Program
{
static void Main (string[] args)
{
Car c = new Car ("Frank", 55);
c.colour = "Green";
Console.WriteLine ("Name = : {0}", c.PetName);
c.DisplayStats ();
Garage carLot = new Garage ();
// Hand over each car in the collection
foreach (Car ch in carLot) {
Console.WriteLine ("{0} is going {1} MPH", ch.PetName, ch.Speed);
}
Console.ReadLine ();
}
class Car
{
//Automatic Properties
public string PetName { get; set; }
public int Speed { get; set; }
public string colour { get; set; }
public void DisplayStats ()
{
Console.WriteLine ("Car Name: {0}", PetName);
Console.WriteLine ("Speed: {0}", Speed);
Console.WriteLine ("Color: {0}", colour);
}
public Car(string petname, int speed) { PetName = petname; Speed = speed; }
}
public class Garage : IEnumerable
{
private Car[] carArray = new Car[4];
// Fill with some car objects on startup.
public Garage ()
{
carArray[0] = new Car ("Rusty", 30);
carArray[1] = new Car ("Clunker", 55);
carArray[2] = new Car ("Zippy", 30);
carArray[3] = new Car ("Fred", 30);
}
public IEnumerator GetEnumerator ()
{
foreach (Car c in carArray) {
yield return c;
}
}
}
}
answered May 1, 2011 at 3:51
hsmithshsmiths
1,24713 silver badges17 bronze badges
0
- Remove From My Forums
-
Question
-
I added an existing item to my project an now I’m getting the error in the Title line.
I added the .cs and the Designer.cs files. The first set of errors start here, how do I fix it?
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; //using System.Linq; using System.Text; using System.Windows.Forms; namespace ProgressBarExample { public partial class ProgressDialog : Form { public ProgressDialog() { InitializeComponent(); } public void UpdateProgress(int progress) { if (progressBar1.InvokeRequired) progressBar1.BeginInvoke(new Action(() => progressBar1.Value = progress)); else progressBar1.Value = progress; } public void SetIndeterminate(bool isIndeterminate) { if (progressBar1.InvokeRequired) { progressBar1.BeginInvoke(new Action(() => { if (isIndeterminate) progressBar1.Style = ProgressBarStyle.Marquee; else progressBar1.Style = ProgressBarStyle.Blocks; } )); } else { if (isIndeterminate) progressBar1.Style = ProgressBarStyle.Marquee; else progressBar1.Style = ProgressBarStyle.Blocks; } } } }
Booney440
-
Edited by
Sunday, September 16, 2018 6:17 PM
updates
-
Edited by
Answers
-
If you look up the definition of Action in the documentation, you will see that it is like this:
public delegate
void Action<in T>(T obj);This means that Action<T> is a delegate that points to a method that takes an argument of type T and returns nothing (void).
However, you are initializing your Action by passing a lambda that takes NO argument and returns nothing. Therefore, it doesn’t match the definition of Action and cannot be used to initialize the Action.
If you want a delegate that points to a method that takes nothing and returns nothing, you can define your own delegate or use one of the existing ones such as MethodInvoker:
progressBar1.BeginInvoke(new
MethodInvoker(() => progressBar1.Value
= progress));
-
Marked as answer by
Booney440
Sunday, September 16, 2018 7:04 PM
-
Marked as answer by
A script error occurred in Unity, but it cannot be solved.
___________________________________________
Assets/Script/UniAction.cs (12,12): error CS0305: Using the generic methodUnityEngine.Component.GetComponent<T>()'requires
1’type argument (s)
___________________________________________
using UnityEngine;
using System.Collections;
public class UniAction: MonoBehaviour
{
private Animator animator;
// Use this for initialization<br>
void Start ()
{
animator = GetComponent ();
}
// Update is called once per frame<br>
void Update ()
{
if (Input.GetKey («up»))
{
transform.position + = transform.forward * 0.02f;
animator.SetBool («Walk» ;, true);
}
else if (Input.GetKey («down»))
{
transform.position + = transform.forward * -0.02f;
animator.SetBool («Walk» ;, true);
}
else if (Input.GetKey («right»))
{
transform.Rotate (0, 5, 0);
}
else if (Input.GetKey («left»))
{
transform.Rotate (0, -5, 0);
}
else
{
animator.SetBool («Walk» ;, false);
}
}
}
___________________________________________
If anyone can understand, thank you. (_ _)
Пока csc /t:library strconcat.cs
с using System.Collections.Generic;
я получаю ошибку
strconcat.cs(9,17): error CS0305: Using the generic type
'System.Collections.Generic.List<T>' requires '1' type arguments
mscorlib.dll: (Location of symbol related to previous error)
Код .cs взят из здесь: Использование Common Language Runtime.
Я проверил описание на msdn, но могу ‘ т компилировать до сих пор
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;
[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize=8000)]
public struct strconcat : IBinarySerialize{
private List values;
public void Init() {
this.values = new List();
}
public void Accumulate(SqlString value) {
this.values.Add(value.Value);
}
public void Merge(strconcat value) {
this.values.AddRange(value.values.ToArray());
}
public SqlString Terminate() {
return new SqlString(string.Join(", ", this.values.ToArray()));
}
public void Read(BinaryReader r) {
int itemCount = r.ReadInt32();
this.values = new List(itemCount);
for (int i = 0; i <= itemCount - 1; i++) {
this.values.Add(r.ReadString());
}
}
public void Write(BinaryWriter w) {
w.Write(this.values.Count);
foreach (string s in this.values) {
w.Write(s);
}
}
}
Я использую Windows 7 x64 с c:WindowsMicrosoft.NETFrameworkv2.0.50727
, а также c:WindowsMicrosoft.NETFramework64v2.0.50727>
Как скомпилировать? Извините, я только начинаю с C # — я искал здесь еще несколько вопросов по SO, и эти советы не помогли мне (
3 ответа
Лучший ответ
Ошибка, описанная в статье, соответствующей CS0305 — количество параметров типа не совпадает.
В вашем случае вы вызываете new List()
с параметрами нулевого типа, когда ожидается один, например: new List<string>()
и соответствующее определение поля private List<string> values;
.
Примечание: если вам по какой-то странной причине нужна неуниверсальная версия, соответствующий класс с именем ArrayList
, но общий List<T>
проще и безопаснее в использовании.
1
Alexei Levenkov
6 Мар 2013 в 12:29
Проблема в том, как указано, вы не указали тип, который храните в списке. Измените этот раздел следующим образом
private List<string> values;
public void Init()
{
this.values = new List<string>();
}
Универсальные типы в C # требуют, чтобы тип, который они использовали, был указан вместо <T>
.
1
Trevor Pilley
6 Мар 2013 в 12:30
System.Collections.Generic.List требует одного аргумента типа, в данном случае это SqlString, поэтому измените следующую часть кода следующим образом:
private List<SqlString> values;
public void Init() {
this.values = new List<SqlString>();
}
0
user1610015
6 Мар 2013 в 12:30
В то время как csc /t:library strconcat.cs
с using System.Collections.Generic;
Я получаю сообщение об ошибке
strconcat.cs(9,17): error CS0305: Using the generic type
'System.Collections.Generic.List<T>' requires '1' type arguments
mscorlib.dll: (Location of symbol related to previous error)
Код .cs взят из здесь: Использование общеязыковой среды выполнения.
Я проверил описание на msdn, но до сих пор не могу скомпилировать
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;
[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined, MaxByteSize=8000)]
public struct strconcat : IBinarySerialize{
private List values;
public void Init() {
this.values = new List();
}
public void Accumulate(SqlString value) {
this.values.Add(value.Value);
}
public void Merge(strconcat value) {
this.values.AddRange(value.values.ToArray());
}
public SqlString Terminate() {
return new SqlString(string.Join(", ", this.values.ToArray()));
}
public void Read(BinaryReader r) {
int itemCount = r.ReadInt32();
this.values = new List(itemCount);
for (int i = 0; i <= itemCount - 1; i++) {
this.values.Add(r.ReadString());
}
}
public void Write(BinaryWriter w) {
w.Write(this.values.Count);
foreach (string s in this.values) {
w.Write(s);
}
}
}
Я использую Windows 7 x64 с c:WindowsMicrosoft.NETFrameworkv2.0.50727
так же как и сигнал c:WindowsMicrosoft.NETFramework64v2.0.50727>
Как скомпилировать? Извините, я только начинаю с С# — я искал некоторые другие вопросы здесь, на SO, и эти советы не помогли мне (
Seeing this error on server startup w/ BotReSpawn 1.0.2:
Error while compiling: BotReSpawn.cs(3407,39): error CS0305: Using the generic method `Facepunch.ComponentExtensions.GetComponent<T,U>(this T, out U)' requires `2' type argument(s)
so BotReSpawn doesn’t load on server start, but once the server is up and I’m connected I can run:
o.reload BotReSpawn
and it loads up just fine.
Share this comment
Link to comment
Hi,
Thanks for reporting. That’s three people who have reported this now but I’m afraid I’ve no idea why it’s happening.
I will do my best to find out.
In the meantime, do you have a plugin that can force BotReSpawn to reload, say, a minute after restart?
Share this comment
Link to comment
7 minutes ago, Steenamaroo said:
Hi,
Thanks for reporting. That’s three people who have reported this now but I’m afraid I’ve no idea why it’s happening.
I will do my best to find out.In the meantime, do you have a plugin that can force BotReSpawn to reload, say, a minute after restart?
I have some automated nodeJS integrations that already detect restarts and can reload the plugin on a delay, so that’s not a problem. Just wanted to report for the sake of reporting. Thank you for your time and attention.
Share this comment
Link to comment
That’s great — I know it’s not the point but at least your usage wont be interrupted.
I’m hoping this is some Rust server install or oxide version related issue that just disappears next wipe, or something, cos I have so few reports,
and no such issue on my windows box, or Mike’s Linux box.
Please let me know if anything changes, though. I’ll be asking around about it.
Share this comment
Link to comment
Of course. I’ll follow up if I have any more details related to this issue. Thank you very much!
Share this comment
Link to comment
Hi,
I’m pretty sure this is fixed now in V1.0.3 but am still awaiting confirmation from anyone who experienced the issue.
Would you mind letting me know, next time you restart the server (with BotReSpawn 1.0.3) ?
Thanks.
Share this comment
Link to comment
Just now, Steenamaroo said:
Hi,
I’m pretty sure this is fixed now in V1.0.3 but am still awaiting confirmation from anyone who experienced the issue.
Would you mind letting me know, next time you restart the server (with BotReSpawn 1.0.3) ?Thanks.
Excellent. I’ve already upgrading to 1.0.3 and my server restarts automatically in aprox 8.5 hours… will follow up with you!
Share this comment
Link to comment
That’s great — Thank you very much.
Share this comment
Link to comment
8 hours ago, Steenamaroo said:
Hi,
I’m pretty sure this is fixed now in V1.0.3 but am still awaiting confirmation from anyone who experienced the issue.
Would you mind letting me know, next time you restart the server (with BotReSpawn 1.0.3) ?Thanks.
No longer seeing the compile error on startup… looks like you sorted it out.
-
1
Share this comment
Link to comment
Thank you!
-
1
Share this comment
Link to comment
Changed Status from Pending to No Response