泛化使用不同函数调用和属性执行相同操作的代码

时间:2018-03-14 03:15:28

标签: c#

我有一个代码块,它使用某个对象的属性作为索引器来调用数组中另一个对象的函数。不太复杂的解释:

// 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班级,但却陷入了如何处理上述差异的问题。我考虑过使用泛型,但所用属性的名称并不总是相同(即使是另一个BarPerson对象)。我怎么能这样做呢?

0 个答案:

没有答案