简体   繁体   中英

Custom properties generics at runtime

I am using the next code to pass parameters to a generic method.

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

example usage

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

this doesnt compile due at the line T.BackgroundImage, its is a property of some controls, Button, Checkbox, etc.

how can I to set a generic way for can do it T.BackGroundImage ?

sorry any error is code in the fly.

You need to do two things to make this work:

  1. Constrain your generics (or remove them), and
  2. Load the resource from the string

This would look like:

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

Note that, in this case, you don't need generics at all. Since Control has the BackgroundImage property, you can just write this as:

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

You could then call this via:

SetBackgroundImage(myButton, "MyProject.Resources.ImgHouse_32.png"); // Use appropriate path
 private void SetValue<T>(T control, String title) where T:Control

You have to tell the compiler that T inherits Control. This is called constraints I believe, and you can set this constraints to classes and interfaces.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM