如何从具有不同类的数组中执行方法
本文关键字:数组 执行 方法 同类 | 更新日期: 2023-09-27 18:24:16
我有两个类:
- 带字段ID的T1类
- T2类,继承自T1类T2具有唯一字段SomeProperty
此外,我有唯一的属性和数组,它包含两种类型的对象(T1和T2)。我需要通过这处房产获得身份证,但我不知道它是如何正确实现的。
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
}
您可以通过强制转换访问该方法。
请事先与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
}