gpt4 book ai didi

c# - 在 C# 中将委托(delegate)转换为通用委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 21:45:50 25 4
gpt4 key购买 nike

简介

我正在使用委托(delegate)来传递和存储单个表单的样式逻辑 Control秒。例如,我有一个包含一些 Button 的委托(delegate)- 像这样的样式逻辑:

button.BackColor = Color.Red;
button.ForeColor = Color.White;
button.FlatStyle = FlatStyle.Flat;

当然还有许多其他类型的控件,如标签、面板等。因此,为了存储所有这些委托(delegate),我使用了 Dictionary<Type, Delegate>。 .

尽管委托(delegate)本身看起来像这样:

delegate void StyleDel<in T>(T control) where T : Control;

所以为了使用字典中的逻辑,Delegate必须转换为 StyleDel<T>首先-随便T可能就在那一刻。


情况

在初始化和存储所有样式后,必须应用样式(使用 StyleDel s)。为此我做了一个函数 StyleControl(control) .

此函数查看控件的类型(例如 Button )并找到相应的 StyleDel来自 Dictionary ,它又应用 ( Button -) 样式。

public void StyleControl<T>(T control) where T : Control
{
Delegate storedDel;
if (_dict.TryGetValue(control.GetType(), out storedDel))
{
// Cast Delegate to StyleDel
var styleDel = (StyleDel<T>) storedDel;

// Execute StyleDel
styleDel(control);
}
}

StyleDel使用 Add 将 s 添加到字典中功能如下:

public bool Add<T>(StyleDel<T> styleDel) where T : Control
{
var inDict = _dict.ContainsKey(typeof(T));
if (!inDict) _dict[typeof(T)] = styleDel;
return !inDict;
}

还有 StyleControl函数被另一个函数调用,这确保一切都以递归方式设置样式:

public void Style<T>(T parent) where T : Control
{
StyleControl(parent);

// The problem might have to do with this
foreach (Control child in parent.Controls) Style(child);
}

问题

InvalidCastException被抛出,说 StyleDel<Button>无法转换为 StyleDel<Control> .所以我相信它在说 T被视为 Control在这一点上,虽然它实际上是一个 Button .

我该如何转换这个 DelegateStyleDel<Button>成功了吗?

最佳答案

您可以通过添加一定程度的间接行为来实现此目的;创建一个调用您的委托(delegate)的 lambda,将参数转换为正确的类型:

Dictionary<Type, StyleDel<Control>> _dict = ...

public bool Add<T>(StyleDel<T> styleDel) where T : Control
{
var inDict = _dict.ContainsKey(typeof(T));
if (!inDict) _dict[typeof(T)] = d => StyleDel((T)d);
return inDict;
}

乍一看,这似乎不是类型安全的,但在这种特殊情况下,这是因为委托(delegate)存储在以参数的真实类型作为键的字典中。因此,预期用途将始终确保始终使用正确类型的参数调用委托(delegate),并且不会发生运行时转换异常。

关于c# - 在 C# 中将委托(delegate)转换为通用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39821232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com