求各位大神详细解答:
我现在定义了很多个图形的类,比如Triangle,Rectangular,Circle等,这些类有坐标,大小等的属性,然后又定义了一个List<object>的容器,把不同类的对象存到容器里面,现在如何遍历这个list容器来获取存在容器中的对象的及其属性呢?
在线跪求解答!!!!!!!!!求指导,先谢谢了。
我现在定义了很多个图形的类,比如Triangle,Rectangular,Circle等,这些类有坐标,大小等的属性,然后又定义了一个List<object>的容器,把不同类的对象存到容器里面,现在如何遍历这个list容器来获取存在容器中的对象的及其属性呢?
在线跪求解答!!!!!!!!!求指导,先谢谢了。
foreach(object obj in list)
{
//obj.Triangle 访问
}
或者Linq to object
看看我弄的这个,弄好了就可以解决你的问题
Triangle tri = new Triangle { Width = 3, Length = 4 };
Rectangular rec = new Rectangular { X = 1, Y = 3 };
Circle cir = new Circle { Radius = 4 }; List<object> list = new List<object>();//这不是List发挥作用的地方,如果非要这样还是使用ArrayList
list.Add(tri);
list.Add(rec);
list.Add(cir); foreach (object item in list)
{
if (item is Triangle)
{
int width = ((Triangle)item).Width;
int length = ((Triangle)item).Length;
}
else if (item is Rectangular)
{
int x = ((Rectangular)item).X;
int y = ((Rectangular)item).Y;
}
else if (item is Circle)
{
int radius = ((Circle)item).Radius;
}
}
//类定义如下
public class Triangle
{
public int Width { get; set; }
public int Length { get; set; }
} public class Rectangular
{
public int X { get; set; }
public int Y { get; set; }
} public class Circle
{
public int Radius { get; set; }
}
{
if(obj is Triangle)
{
Triangle t = obj as Triangle;
t.xxx....
t.yyy....
}
else if(obj is Rectangular)
{
Rectangular r = obj as Rectangular;
r.xxx....
r.yyy....
}
//....
}
你应该写一个 比如 图形类而 那些画图的 继承于这个类
list 类型为 基类
也就是图形类
class Program
{
static void Main(string[] args)
{
User user = new User("aaa");
List<object> list = new List<object>();
list.Add(new User("user"));
list.Add(new Person("female"));
object o = list[0];
if (o.GetType()==typeof(User))
{
Console.WriteLine(((User)o).Name);
}
else if (o.GetType() == typeof(Person))
{
Console.WriteLine(((Person)o).Gender);
}
Console.ReadLine();
}
} class User
{
public string Name{ get;set;} public User(string name)
{
this.Name = name;
}
} class Person
{
public string Gender {get; set;} public Person(string gender)
{
this.Gender = gender;
}
}测试结果是“user”,没问题。List<object>中返回的是详细的类名,而不是object数组
从list取出之后先转换到基类,判断类型。
private void button8_Click(object sender, EventArgs e)
{
object obj = propertyGrid1.SelectedObjects;//就是每个图形类的属性窗口的内容,这个好像只能是system.object[]类型,不能转换;这个属性窗口中的属性是自己定义的。
mylist.addwidget(obj);//这个就是将每个图形的实例添加到List中。
}
所以用GetType返回的list容器中的内容都是object,这样有办法读取那些东西吗?下面是运行的一个窗口截图:
我觉得是这样的,即使一个User类在强制转换为object后再放入到List中后,当取出后采用反射,还是会反射到User类型的,这个我测试了,我可以确定没问题。我现在怀疑,propertyGrid1.SelectedObjects返回的就是object的实例。 propertyGrid1是个什么控件,SelectedObjects返回的又是什么?
[email protected] 不知道现在这邮箱还好不好用