我有2个课程:
此外,我还有唯一的属性和数组,它包含两个类型对象(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
}
答案 0 :(得分:1)
您可以通过强制转换来访问该方法。
事先用is
运算符检查类型。跟随强制转换以防止使用try / catch块,您也可以使用foreach而不是for
来简化代码:
public int GetObjectIDByProperty(Array Objects, int property)
{
foreach(T_One myT_One in Objects)
{
//Check Type with 'is'
if (myT_One is T_Two))
{
//Now cast:
T_Two myT_Two = (T_Two)myT_One;
if (myT_Two.Property == property)
return myT_Two.ID;
}
}
return -1; //Object with this property didn't exist
}