运行时自定义属性泛型

时间:2013-11-13 01:10:19

标签: 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?

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

2 个答案:

答案 0 :(得分:3)

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

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

    这看起来像是:

    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
    

答案 1 :(得分:1)

 private void SetValue<T>(T control, String title) where T:Control

你必须告诉编译器T继承Control。我认为这称为约束,您可以将此约束设置为类和接口。

http://msdn.microsoft.com/en-us/library/vstudio/d5x73970.aspx