在不同类型上调用相同的方法

时间:2011-08-13 20:07:03

标签: c# coding-style types

编辑:让我们假设实际上的类共享一个接口!对我来说很重要......


由于我不知道的原因,例如有两个WPF类,它们具有相同的签名方法:

所以我一直想知道(哎呀)我应该如何构建一个最终调用上述方法的方法(例如,类型检查和异常)。

我将发布我倾向于做的事情,但我正在寻找更有经验的人会推荐的内容。

4 个答案:

答案 0 :(得分:2)

我的方法:

public static void Animate(object target)
{
    target.ThrowIfNull(); //Extension
    if (!(target is Animatable || target is UIElement))
        throw new ArgumentException("The target is not animatable");

    //Construct animation

    (target as dynamic).BeginAnimation(property, animation);
}

答案 1 :(得分:1)

如果您提议,两个类共享相同的接口IAnimatable

((IAnimatable)target).BeginAnimation(property, animation);

应该足够了

Here是文档

答案 2 :(得分:0)

public static void Animate(this object target, DependencyProperty property, AnimationTimeline animation)
{
    target.ThrowIfNull();
    DoAnimate(target as dynamic);
}

private static void DoAnimate(object target, DependencyProperty property, AnimationTimeline animation)
{
    throw new ArgumentException("The target is not animatable")
}

private static void DoAnimate(Animatable target, DependencyProperty property, AnimationTimeline animation)
{
    target.BeginAnimation(property, animation);
}

private static void DoAnimate(UIElement target, DependencyProperty property, AnimationTimeline animation)
{
    target.BeginAnimation(property, animation);
}

在我看来,它更清洁。

更新使用AnimationContext的示例

class AnimationContext
{
    private readonly DependencyProperty property;
    private readonly AnimationTimeline animation;

    public AnimationContext(DependencyProperty property, AnimationTimeline animation)
    {
        this.property = property;
        this.animation = animation;
    }

    public void Animate(UIElement target)
    {
        target.BeginAnimation(property, animation);
    }

    public void Animate(Animatable target)
    {
        target.BeginAnimation(property, animation);
    }

    public void Animate(object target)
    {
        throw new ArgumentException("The target is not animatable");
    }
}

static class AnimateExtensions
{
    public static void Animate(this object target, DependencyProperty property, AnimationTimeline animation)
    {
        target.ThrowIfNull();
        new AnimationContext(property, animation).Animate(target as dynamic);
    }
 }

答案 3 :(得分:0)

在对两个类的编辑没有从同一个接口继承之后,答案是使用以下之一:

  1. 反思
  2. Dynamic
  3. 这些当然不会检查该方法是否存在直到运行时,但我认为这在问题中是隐含的。

    给定以下两个类A和B,它们包含具有相同签名的方法,但不实现相同的接口:

    class A
        public void Handle(string s) {
            Console.WriteLine("Hello from A: " + s);
        }
    }
    

    class B
        public void Handle(string s) {
            Console.WriteLine("Hello from B: " + s);
        }
    }
    

    您可以创建一个方法来处理具有该签名的方法的任何对象,如下所示:

    static void HandleObject(dynamic anything) {
        anything.Handle("It works!");
    }
    

    HandleObject基本上将任何对象作为输入,并在运行时尝试盲目地调用一个名为Handle的方法。如果对象没有Handle方法,则调用将在运行时失败。

    编译器无法帮助(或停止)动力学。故障被推迟到运行时间:)