2013-07-22 34 views
-3

执行方法我有2类:如何从阵列与不同类

  1. 类T1与字段ID。
  2. 类T2继承自T1 类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 
} 
+1

代码,告诉我们您的代码首先 – wudzik

+0

也许你可以提供一些例子作为代码。我无法掌握你想要达到的目标。 –

+0

没有一些代码,我们只能给你一个答案:'M-m-m-magic!' – Nolonar

回答

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 
    } 
+0

非常感谢你,'is'运算符是我所需要的! –

+1

不客气 - 只是一个小小的评论:事实上,在将它们投射到T_One上之前,您还应该检查Array中对象的类型,因为您没有运行时保证它们都是T_One类型。当您使用不从T_One继承的对象扩展列表时,您可能会遇到异常 – Marwie