-3

我有 2 节课:

  1. 具有字段 ID 的 T1 类。
  2. 从 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
}
4

1 回答 1

1

您可以通过强制转换访问该方法。

is请事先使用 Operator检查类型。后跟强制转换以防止使用 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
    }
于 2013-07-22T09:35:03.130 回答