在不实例化新类的情况下重用函数的最简单方法 [英] Easiest way to re-use a function without instantiation a new class
问题描述
我目前有一个看起来像这样的函数:
I currently have a function that looks like this:
public void AnimateLayoutTransform(object ControlToAnimate)
{
//Does some stuff
}
我在许多不同的项目中都使用了此功能,因此我希望它非常可重用.因此,现在我将其保存在一个.cs文件中,该文件包含在一个命名空间和一个类中:
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);
重用一个函数似乎需要做很多工作.至少有什么方法可以使用函数而不创建类的新实例吗?类似于我们如何在不创建新double
的情况下Double.Parse()
?
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
?
推荐答案
一种选择是使其成为常规的静态方法.如果您使用的是C#3.0或更高版本,则可以选择将其作为扩展方法:
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
}
}
然后您可以编写:
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.
这篇关于在不实例化新类的情况下重用函数的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!