2012-11-06 41 views
0

如果让我们说我有一个带有ListView和Update()函数的FormA。然后,我也有一个数学类与函数A()有一些魔术......委托可以用来从A()调用Update()吗?或者,还有更好的方法?我意识到从另一个类更新一个GUI形式是有风险的。从另一个类调用ListView更新函数...可能吗?

回答

2

是的。只要Math类不知道它的实际调用,它就没有那么大的风险。你只要给它一个粗略的想法通过它从你的表指向所需的功能:

public class MathClass { 
    public Action FunctionToCall { get; set; } 

    public void DoSomeMathOperation() { 
     // do something here.. then call the function: 

     FunctionToCall(); 
    } 
} 

在你的表格你可以这样做:

// Form.cs 
public void Update() { 
    // this is your update function 
} 

public void DoMathStuff() { 
    MathClass m = new MathClass() { FunctionToCall = Update }; 
    m.DoSomeMathOperation(); // MathClass will end up calling the Update method above. 
} 

你MathClass调用Update,但它没有知识告诉它调用Update的对象或更新的位置,使它比将对象紧密耦合在一起更安全。

+0

真的不错的代码! :)我会测试这一点,也从另一个线程(因为它的想法).. –

相关问题