Skip to main content
 首页 » 编程设计

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

2024年02月13日12wuhuacong

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

 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)); 
} 

请注意,在这种情况下,您根本不需要泛型。因为 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