你需要做两件事来完成这项工作:
- 约束你的泛型(或删除它们),并且
- 从字符串加载资源
这看起来像:
private void SetBackgroundImage<T>(T control, string title) where T : Control
{
control.BackgroundImage =
new Bitmap(
typeof(this).Assembly.GetManifestResourceStream(title));
}
请注意,在这种情况下,您根本不需要泛型。由于Control具有BackgroundImage属性,您可以将其写为:
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