c# - 运行时自定义属性泛型

标签 c# .net generics

我正在使用下一个代码将参数传递给通用方法。

 private void SetValue<T>(T control, String title)
 {
      T.BackgroundImage = title;
 }

示例用法

SetValue<Button>(myButton,"Resource.ImgHouse_32.etc")

由于在 T.BackgroundImage 行无法编译,它是一些控件、Button、Checkbox 等的属性。

我如何设置一个通用的方式来实现 T.BackGroundImage?

抱歉,任何错误都是在运行中的代码。

最佳答案

你需要做两件事来完成这项工作:

  1. 限制您的泛型(或删除它们),以及
  2. 从字符串中加载资源

这看起来像:

private void SetBackgroundImage<T>(T control, string title) where T : Control
{
    control.BackgroundImage = 
                new Bitmap(
                    typeof(this).Assembly.GetManifestResourceStream(title));
}

请注意,在这种情况下,您根本不需要泛型。因为 ControlBackgroundImage属性,你可以这样写:

private void SetBackgroundImage(Control control, string title)
{
    control.BackgroundImage = 
                new Bitmap(
                    typeof(this).Assembly.GetManifestResourceStream(title));
}

然后您可以通过以下方式调用它:

SetBackgroundImage(myButton, "MyProject.Resources.ImgHouse_32.png"); // Use appropriate path

关于c# - 运行时自定义属性泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19943350/

相关文章:

swift - 在另一个通用协议(protocol)类型中使用一个通用协议(protocol)类型

c# - 如何解决asp.net core mvc项目中的 "view not found"异常

c# - 文件/文件夹结构的递归搜索

c# - 有没有办法阻止这段代码每次都打开一个新的浏览器窗口?

java - 使用更窄的参数化覆盖泛型方法

java - Groovy 不执行 Java-Method(签名包括泛型)

c# - 带有自定义错误信号的条件行为

c# - 有什么方法可以将复选框列表绑定(bind)到 asp.net mvc 中的模型

c# - 如何只获取 DataTable 中具有相同 ID 的最新条目?

c# - SetWindowLong 启用/禁用单击表单