[英]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. 你也可以为您的界面
NavObject
和GameObject
实现一个包含了所有需要你中的属性/方法FollowForce
和AddForce
方法。
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
作为参数的FollowForce
和AvoidForce
函数也必须接受“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
并在扩展它们NavObject
和GameObject
。 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
然后,
FollowForce
和AvoidForce
静态函数参数也必须是TrackedObject
类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.