简体   繁体   English

c#重载方法的泛型函数

[英]c# generic function for overloaded methods

I have two methods, FollowForce() and AvoidForce() which are overloaded to accept either a NavObject or a GameObject. 我有两个方法,FollowForce()和AvoidForce(),它们被重载以接受NavObject或GameObject。 Is there a way to simplify the Follow() function to accept both types? 有没有办法简化Follow()函数接受这两种类型?

public void Follow(NavObject target){ 
        if(isFollowing){Body.AddForce(FollowForce(target));}
        if(isAvoiding){Body.AddForce(AvoidForce(target));}
    }

public void Follow(GameObject target){ 
        if(isFollowing){Body.AddForce(FollowForce(target));}
        if(isAvoiding){Body.AddForce(AvoidForce(target));}
    }

I tried the following, but got cannot convert 'T' expression to type 'NavObject' : 我尝试了以下内容,但得到了cannot convert 'T' expression to type 'NavObject'

public void Follow <T>(T target){ 
        if(isFollowing){Body.AddForce(FollowForce(target));}
        if(isAvoiding){Body.AddForce(AvoidForce(target));}
    }

Potentially, you don't even need to use Generics with this. 可能,您甚至不需要使用泛型。 You could also create an interface for your NavObject and GameObject to implement that contains all of the properties/methods that are needed within your FollowForce and AddForce methods. 你也可以为您的界面NavObjectGameObject实现一个包含了所有需要你中的属性/方法FollowForceAddForce方法。

public void Follow(IHaveForce target)
{
    if (isFollowing)
    {
        Body.AddForce(FollowForce(target));
    }
    if (isAvoiding)
    {
        Body.AddForce(AvoidForce(target));
    }
}

Then your other methods would need to be set up like this: 然后你需要设置其他方法,如下所示:

public Force FollowForce(IHaveForce target)
{
    // Do your work...
}

public Force AvoidForce(IHaveForce target)
{
    // Do your work...
}

The only reason you would need to utilize Generics would be if you want to enforce the same type throughout. 你需要使用泛型的唯一原因是你想在整个过程中强制执行相同的类型。 In the minimal scenario you have provided, it doesn't seem as though that's what you need. 在您提供的最小场景中,似乎并不是您需要的。 If you want to use Generics anyway, you can have your Generic type implement IHaveForce as well. 如果你想使用Generics,你可以使用Generic类型实现IHaveForce

您接受target作为参数的FollowForceAvoidForce函数也必须接受“T”类型

If your Objects share functionality you should introduce an abstract base class or an interface TrackedObject and extend them in your NavObject and GameObject . 如果你的对象共享功能,您应该引入一个抽象基类或接口TrackedObject并在扩展它们NavObjectGameObject You then can write the following 然后,您可以编写以下内容

public void Follow(TrackedObject target){ 
    if(isFollowing){Body.AddForce(FollowForce(target));}
    if(isAvoiding){Body.AddForce(AvoidForce(target));}
}

Your static functions parameters of FollowForce and AvoidForce must then also be of type TrackedObject 然后, FollowForceAvoidForce静态函数参数也必须是TrackedObject类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM