I currently have a fu开发者_运维技巧nction that looks like this:
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Does some stuff
}
I use this function in a lot of different projects, so I want it to be very reusable. So for now I have it in a .cs file, enclosed in a namespace and a class:
namespace LayoutTransformAnimation
{
public class LayoutAnims
{
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Do stuff
}
}
}
The problem with this is that to use this one function in a given project, I have to do something like
new LayoutTransformAnimation.LayoutAnims().AnimateLayoutTransform(mygrid);
Which just seems like a lot of work to reuse a single function. Is there any way to, at the very least, use the function without creating a new instance of the class? Similar to how we can Double.Parse()
without creating a new double
?
One option is to make it a normal static method. An alternative - if you're using C# 3.0 or higher - is to make it an extension method:
public static class AnimationExtensions
{
public static void AnimateLayoutTransform(this object controlToAnimate)
{
// Code
}
}
Then you can just write:
mygrid.AnimateLayoutTransform();
Can you specify the type of the control to animate any more precisely than "Object"? That would be nicer... for example, can you only really animate instances of UIElement
? Maybe not... but if you can be more specific, it would be a good idea.
You could make it into a static method.
MSDN Example
I find it useful to have a static util class with static methods in them which can be used within the project namespace.
public static class YourUtilsClass
{
public static Void YourMethod()
{
//do your stuff
}
}
You can call it like so: YourUtilsClass.YourMethod()
namespace LayoutTransformAnimation
{
public class LayoutAnims
{
public static void AnimateLayoutTransform(object ControlToAnimate)
{
//Do stuff
}
}
}
LayoutTransformAnimation.LayoutAnims.AnimateLayoutTransform(something);
精彩评论