我有一个代码块,它使用某个对象的属性作为索引器来调用数组中另一个对象的函数。不太复杂的解释:
// Random example class
class Foo
{
private string message;
public Foo(string msg) { this.message = msg; }
public void Speak() { Console.WriteLine(message); }
}
// In another class elsewhere
private static Foo[] foos =
{
new Foo("hello"),
new Foo("sup")
};
void doStuff(int id)
{
Bar b = database.GetBar(id); // Get object
if (b.SomeIntProperty < foos.Length)
{
// Use object property as index
foos[b.SomeIntProperty].Speak(); // Call this exact Foo function
b.SomeIntProperty++; // Increment object property
database.UpdateBar(b); // Save object
}
}
// In yet another class, with another Foo[] array called 'stuff'
void doOtherStuff(int id)
{
Person p = database.GetPerson(id); // Get object
if (p.SomeOtherIntProperty < stuff.Length)
{
// Use object property as index
stuff[p.SomeOtherIntProperty].Speak(); // Call this exact Foo function
p.SomeOtherIntProperty++; // Increment object property
database.UpdatePerson(p); // Save object
}
}
从注释中可以看出,完全相同的事情顺序 - 只是使用了不同的对象类型和属性。我试图把事情搞砸到一个FooList
班级,但却陷入了如何处理上述差异的问题。我考虑过使用泛型,但所用属性的名称并不总是相同(即使是另一个Bar
或Person
对象)。我怎么能这样做呢?