c# - 委托(delegate)细节

标签 c# delegates xna

我在与我正在处理的项目的类(class)中遇到问题。该类是一个接受标签和值的 GUI 组件。这里的想法是,用户可以指定一个标签,然后从任何地方链接一个值(更具体地说,该值的 ToString 方法),以便每次更新该值时,GUI 组件也会更新。这是其设置方式的基础知识:

public delegate string GUIValue();

public class GUIComponent
{
    GUIValue value = null;    // The value linked in
    string label = "";        // The label for the value
    string text = "";         // The label and value appended together

    public GUIComponent(string Text, GUIValue Value)
    {
        this.text = Text;
        this.value += Value;
    }

    public void Update()
    {
        this.text = this.label + this.value();
    }
}

然后我这样调用它

GUIComponent component = new GUIComponent("Label: ",
                                new GUIValue(this.attribute.ToString));

代码编译正确,组件确实显示,并显示赋予它的属性的初始值,但是,只要属性值更改,它就不会更新。

我的问题是,我是否一开始就正确设置了这个设置,如果是这样,为什么它不起作用。我最初的想法是它只接受 ToString 方法返回的第一个值,因为它不接受任何参数,但有人可以验证这一点吗?

最佳答案

这段代码:

new GUIValue(this.attribute.ToString)

不会导致每次属性改变时都调用方法。您必须存储委托(delegate)并在每次有人更改“属性”时调用它。像这样的东西:

private event GUIValue attributeChanged = () => this.attribute.ToString();

private String attribute;

// This is a property that sets the value of attribute
public String Attribute { get { return attribute; } set { attribute = value; attributeChanged(); } }

// Now you can initialize the component using:
// GUIComponent component = new GUIComponent("Label: ", this.attributeChanged);

关于c# - 委托(delegate)细节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4901522/

相关文章:

delegates - Storyboard中的SplitView,无法连接委托(delegate)

C# 检查文件夹避免阻塞 UI

XNA 不显示我自己的 fbx 模型的纹理

图形问题 : How do I restrict the mouse cursor to within a circle?

c# - 删除最后一行以外的任何行后,如何对自动增量列值重新排序?

c# - Google Drive API v3 (C# .NET) 按标题搜索文件夹/文件时抛出 RequestError Invalid Value [400]

c# - 使用 Oracle.DataAccess.Client;下载并安装 OPD.NET 后未找到

c# - 在 ASP.NET MVC 3 中使用枚举

ios - 我的自定义 RxDelegateProxy 立即处理

c# - 如何确定矩形的哪一边与圆碰撞