C# 通用UI更新方法

C# 通用UI更新方法,c#,winforms,asynchronous,async-await,C#,Winforms,Asynchronous,Async Await,我目前正在使用async并在C#中等待,我想创建一个方法来更新UI,而不必面对跨线程更新的问题。这就是我现在所拥有的 模型类: public class UIModel { public string ControlId { get; set; } public Type TypeOfControl { get; set; } public string PropertyName { get; set; } public object Data { get;

我目前正在使用async并在C#中等待,我想创建一个方法来更新UI,而不必面对跨线程更新的问题。这就是我现在所拥有的

模型类:

public class UIModel
{
    public string ControlId { get; set; }
    public Type TypeOfControl { get; set; }

    public string PropertyName { get; set; }

    public object Data { get; set; }
    public Type TypeOfData { get; set; }
}
UI更新程序方法:

private void UIUpdater(UIModel model)
{
    var control = this.Controls.Find(model.ControlId, true).FirstOrDefault() as model.TypeOfControl.GetType(); // <- not valid
    // set control's model.PropertyName using model.Data
}
上面的代码为您提供了一个错误,因为
as
运算符希望在
as
关键字not和表达式后面有一个类型

从C#规范:

在形式为E作为T的操作中,E必须是表达式,T必须是引用类型、已知为引用类型的类型参数或可为空的类型

您可以使用
FirstOrDefault
过滤
控件
集合。我尝试了下面的代码,它与您提供的数据一起工作,正确设置了
TextBox
Text
属性

 var result = this.Controls.Find(model.ControlId, true).FirstOrDefault(x => x.GetType() == model.TypeOfControl);

 PropertyInfo prop = result.GetType().GetProperty(model.PropertyName, BindingFlags.Public | BindingFlags.Instance);
 if (null != prop && prop.CanWrite)
 {
    prop.SetValue(result, model.Data, null);
 }   

但是类型仍然是Control,那么如何根据UIModel设置属性?例如,控件没有名为DataSource的属性(用于DataGridView)。返回的类型将是在
UIModel
中指定的类型,因为
GetType
返回对象的实际类型。我对它进行了测试并更新了答案,它按预期工作。
var control = this.Controls.Find(model.ControlId, true).FirstOrDefault() as model.TypeOfControl.GetType()
 var result = this.Controls.Find(model.ControlId, true).FirstOrDefault(x => x.GetType() == model.TypeOfControl);

 PropertyInfo prop = result.GetType().GetProperty(model.PropertyName, BindingFlags.Public | BindingFlags.Instance);
 if (null != prop && prop.CanWrite)
 {
    prop.SetValue(result, model.Data, null);
 }