Easiest way to re-use a function without instantiation a new class

心不动则不痛 提交于 2019-12-20 02:38:13

问题


I currently have a function 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?


回答1:


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.




回答2:


You could make it into a static method.

MSDN Example




回答3:


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()




回答4:


namespace LayoutTransformAnimation 
{ 
    public class LayoutAnims 
    { 
        public static void AnimateLayoutTransform(object ControlToAnimate) 
    { 
        //Do stuff 
    } 
} 

}

LayoutTransformAnimation.LayoutAnims.AnimateLayoutTransform(something);


来源:https://stackoverflow.com/questions/3119087/easiest-way-to-re-use-a-function-without-instantiation-a-new-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!