Cannot Add to generic list
Firstly I apologise for the oversimplification, but I have this issue which is driving me crazy. It should work - it's simple code, nothing fancy.......
I have this object
public class Stuff
{
private int intStuff;
private string strStuff;
public Stuff(int StuffID, string Stuff)
{
intStuff = StuffID;
strStuff = Stuff;
}
public int StuffID
{
get { return intStuff; }
set { intStuff = value; }
}
public string Stuff
{
开发者_如何学C get{return strStuff;}
set{strStuff=value;}
}
}
Which is used in this class:
public class StuffandThings
{
private List<Stuff> lstMyStuff;
public List<Stuff> StuffList
{
set { lstMyStuff = value; }
get { return lstMyStuff; }
}
public StuffandThings()
{
lstMyStuff = new List<Stuff>();
}
}
Which is declared as a static in Global.asax <<<< this may be important
public static StuffAndThings MyStuff;
protected void Application_Start(object sender, EventArgs e)
{
MyStuff = new StuffandThings();
}
And when I use it in code:
foreach (string strStuff in lstStuff)
{
objStuff = new Stuff(intStuff,strStuff);
Global.MyStuff.StuffList.Add(objStuff);
}
It compiles and I can run in debug (it's a WCF Web service), my variables (intStuff and lstStuff) are all valid.but when I click on Service.svc in the browser I get the following error.
CS1502: The best overloaded method match for 'System.Collections.Generic.List.Add(Stuff)' has some invalid arguments
I don't think I can see the wood for the trees with this one and the interwebs have been no help.
Aso, all my other objects and functions in the global object are fine - hashtables mostly, and my code ran until I tried to add this functionality. I would use a hashtable but I would need the key to not be unique;
Any Ideas, please?
Thanks
P
You should declare the type of objStuff inside the loop. Always declare variables inside the smallest scope you can:
Stuff objStuff = new Stuff(intStuff,strStuff);
Global.MyStuff.StuffList.Add(objStuff);
If this fails to compile because objStuff is already in use in the parent scope then find a new name - objStuff2 for example, then everything should work.
Where is objStuff declared in your code? You might be picking up the declaration of something else that also happens to be called objStuff but is actually unrelated.
精彩评论