我有 2 节课:
- 具有字段 ID 的 T1 类。
- 从 T1 类 T2 继承的 T2 类具有唯一字段 SomeProperty。
我也有独特的属性和数组,它包含两个类型对象(T1 和 T2)。我需要通过这个属性获取 ID,但我不知道它是如何正确实现的。
public class T_One
{
protected int id;
public T_One(int foo)
{
id = foo;
}
public int ID
{
get { return id; }
}
}
public class T_Two : T_One
{
protected int someProperty;
public T_Two(int id, int foo) : base(id)
{
someProperty = foo;
}
public int Property
{
get { return someProperty; }
}
}
//I have some solution, but I think it's BAD idea with try-catch.
public int GetObjectIDByProperty(Array Objects, int property)
{
for(int i = 0; i < Objects.Length; i++)
{
try
{
if (((T_Two)(Objects.GetValue(i))).Property == property)
{
return ((T_Two)Objects.GetValue(i)).ID;
}
}
catch
{
//cause object T_one don't cast to object T_Two
}
}
return -1; //Object with this property didn't exist
}