我正在使用下一个代码将参数传递给通用方法。
private void SetValue<T>(T control, String title)
{
T.BackgroundImage = title;
}
示例用法
SetValue<Button>(myButton,"Resource.ImgHouse_32.etc")
由于在 T.BackgroundImage 行无法编译,它是一些控件、Button、Checkbox 等的属性。
我如何设置一个通用的方式来实现 T.BackGroundImage?
抱歉,任何错误都是在运行中的代码。
最佳答案
你需要做两件事来完成这项工作:
- 限制您的泛型(或删除它们),以及
- 从字符串中加载资源
这看起来像:
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
关于c# - 运行时自定义属性泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19943350/