[英]Conversion of var to class type in C#?
I am new to C# and was going through ArrayList
. 我是C#的新手,正在经历ArrayList
。 My question is can we store different datatype - different classes, different structures into ArrayList and access them. 我的问题是我们可以将不同的数据类型-不同的类,不同的结构存储到ArrayList中并访问它们。 I could see that I can add them but I am not sure on how can we retrieve it. 我可以看到可以添加它们,但是我不确定如何获取它。 I tried retrieving by using the datatype name ie class name but I am seeing that the first member data is missing while I am printing the output. 我尝试使用数据类型名称(即类名称)进行检索,但是我看到在打印输出时缺少第一个成员数据。 What concept am I missing here? 我在这里想念什么概念?
class OSPF_Area
{
public string AreaId { get; set; }
public string AreaName { get; set; }
public int AreaNumberofRoutes { get; set; }
}
class OSPFLinkPacket
{
public int LinkPacketCounts { get; set; }
public int NumberOfHelloPacket { get; set; }
public string LSAType { get; set; }
}
static void Main(string[] args)
{
OSPF_Area ospfArea1 = new OSPF_Area();
ospfArea1.AreaId = "0.0.0.1";
ospfArea1.AreaId = "non-backbone";
ospfArea1.AreaNumberofRoutes = 14;
OSPFLinkPacket ospfLink1 = new OSPFLinkPacket();
ospfLink1.LinkPacketCounts = 20;
ospfLink1.LSAType = "Type4";
ospfLink1.NumberOfHelloPacket = 40;
ArrayList OSPFInfo = new ArrayList();
OSPFInfo.Add(ospfLink1);
OSPFInfo.Add(ospfArea1);
foreach(var val in OSPFInfo)
{
if(val.GetType().Name == "OSPF_Area")
{
Convert.ChangeType(val, typeof(OSPF_Area));
OSPF_Area area = (OSPF_Area)val;
Console.WriteLine(area.AreaId);
Console.WriteLine(area.AreaName);
Console.WriteLine(area.AreaNumberofRoutes);
}
}
Console.ReadLine();
}
The output is: 输出为:
non-bacbone 非烟草
14 14
I am not sure why the area-id didn't get printed. 我不确定为什么没有打印区域ID。
Firstly, I'd advise you to not use ArrayList
. 首先,我建议您不要使用ArrayList
。 Use List<T>
where you can, although storing different types of objects in a list is a bit of an anti-pattern to start with. 尽管可以在列表中存储不同类型的对象,但是可以使用List<T>
来作为反模式。
Convert.ChangeType
doesn't do anything for you, and you should use is
or as
. Convert.ChangeType
不会为您做任何事情,您应该使用is
或as
。 For example: 例如:
OSPF_Area area = val as OSPF_Area;
if (area != null)
{
Console.WriteLine(area.AreaId);
Console.WriteLine(area.AreaName);
Console.WriteLine(area.AreaNumberofRoutes);
}
The problem for the output is almost certainly due to the typo in the first lines of Main
: 输出的问题几乎可以肯定是由于Main
的第一行中的错字引起的:
ospfArea1.AreaId = "0.0.0.1";
ospfArea1.AreaId = "non-backbone";
... you're not assigning anything to AreaName
. ...您没有为AreaName
分配任何AreaName
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.