المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Generics and Arrays Help Please!



C# Programming
07-10-2009, 03:18 PM
Hi All

Here is a cut down version of the code that I am working on and having problems with
The first Code Block works fine

public class MyBase
{
public string MyName;
public object MyValue;

public T ValueTyped
{
get {return (T)MyValue; }
set { MyValue = (object)value; }
}

public MyBase(string NewName, T DefaultValue)
{
MyName = NewName;
ValueTyped = DefaultValue;
}
}


public class MyString : MyBase
{
public int MyMaxLength = 50;
public MyString(string NewName, string DefaultValue, int MaxLength)
: base(NewName, DefaultValue)
{
MyMaxLength = MaxLength;
}
}

public class MyInt : MyBase
{
public int MyMaxValue = 100;
public MyInt(string NewName, int DefaultValue, int MaxValue)
: base(NewName, DefaultValue)
{
MyMaxValue = MaxValue;
}
}

public class Testing
{
public void test()
{
MyString _string = new MyString("Name","",20);
MyInt _int = new MyInt("Size",10,72);
}
}

Up to here all is OK. The next Code block falls over. I am try to create an array that can contain MyString and MyInt classes using the base class MyBase so that it can be used like in class testing2.test

public class MyBaseArray
{
List ListAll = new List;

public void AddMyBase(MyBase Item)
{
ListAll.Add(Item);
}

public MyBase Find(string name)
{
foreach (MyBase _MyBase in ListAll)
{
if (_MyBase.MyName == name)
{
return _MyBase;
}
}
throw new Exception("Item Not in list");
}
}

public class testing2
{
public void test()
{
MyBaseArray MyBases = new MyBaseArray();
MyBases.AddMyBase((MyBase)new MyString("Name1","Fred",20));
MyBases.AddMyBase((MyBase)new MyInt("Size1",10,72));
MyBases.AddMyBase((MyBase)new MyString("Name2","George",20));
MyBases.AddMyBase((MyBase)new MyInt("Size2",8,72));

MessageBox.show(MyBases.Find("Name2").ValueTyped);
int FontSize = MyBases.Find("Size2").ValueTyped
}
}


The Idea works If I remove the Generics from MyBase and make ValueTyped return an Object.

The question, is it posible to have a array of MyBase where I can use .ValueTyped to return a string for MyString and an int for MyInt.
without have to do any type casing?

MessageBox.show(((MyString)MyBases.Find("Name2")).ValueTyped)
int FontSize = ((MyInt)MyBases.Find("Size2")).ValueTyped
or
MessageBox.show((string)MyBases.Find("Name2").ValueTyped)
int FontSize = (int)MyBases.Find("Size2")).ValueTyped


The original code above is far more readable.

Generics did seem like the way to go until I hit this problem.

Thanks any help.
James