执行方法我有2类:如何从阵列与不同类
- 类T1与字段ID。
- 类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
}
代码,告诉我们您的代码首先 – wudzik
也许你可以提供一些例子作为代码。我无法掌握你想要达到的目标。 –
没有一些代码,我们只能给你一个答案:'M-m-m-magic!' – Nolonar