C#: Class to use with Object
How can I create a class (in a DLL) that is used with a specific object? Like for instance, a class tha开发者_如何学运维t Bitmaps call on to do certain things. e.g.
Bitmap bmp = new Bitmap;
bmp.ThingToDo():Have a look at Extension Methods.
You can add your method to the class Bitmap like the following:
public static class CustomExtension
{
public static void ThingToDo(this Bitmap bitmap)
{
// add your functionality here and use bitmap
}
}
Good luck!
Here's an example of an Extension Method including the Class and Namespace
using System.Runtime.CompilerServices;
namespace Extensions
{
public static class BitmapExtensions
{
[Extension()]
public static void MakeMyImageCool(Bitmap img)
{
//'# do something with your image here.
}
}
}
And then to call it
Bitmap img = MySourceImage;
img.MakeMyImageCool();
Notice how even though there is a parameter request in the method, you are not passing a parameter in the call. That's because the extension method already uses the "img" as the parameter.
精彩评论