2013-07-25 60 views
0

我读过MSDN网站上的c#模板(泛型)与C++不一样。我有两个不同的对象,它具有组件转换有可能以某种方式提供它与“对象”,而不是特定的组件?C#通用函数调用

我想进行如下调用,因为两个对象都有一个转换组件。

collisionCheck(Me, this) 

否则我可以做得一样好:

collisionCheck(Me.transform, this.transform) 

但我想尽可能多地隐藏在前端。 (下面的例子是没有馈电变换组件)

public void collisionCheck(object enemy, object me){ 
    if(me.transform.x < enemy.transform.x) 
     print("foo"); 
} 

如果您有任何提示,它会很好!

回答

3

您可能需要继承而不是泛型。

public interface IPositioned 
{ 
    float X { get; } 
    float Y { get; } 
} 

public class Me: IPositioned { /* ... */ } 
public class Enemy: IPositioned { /* ... */ } 

/* ... */ 
public void CollisionCheck(IPositioned me, IPositioned enemy) 
{ 
    if (me.X < enemy.X) 
    { 
     Console.Write("foo"); 
    } 
} 
+0

现货上。 +1 ... – spender

0

你可以用这样的东西去。但我同意你可能想在基类上实现CollisionCheck实现并使用继承。

public class Transform 
{ 
    public float X { get; set; } 
    public float Y { get; set; } 
} 

public interface IHasTransform 
{ 
    Transform SomeTransform { get; set; } 
} 

public class You : IHasTransform 
{ 
    public Transform SomeTransform { get; set; } 
} 

public class Me : IHasTransform 
{ 
    public Transform SomeTransform { get; set; } 

    public void CollisionCheck<T>(T other) where T : IHasTransform 
    { 
     if (this.SomeTransform.X < other.SomeTransform.X) 
      Console.WriteLine("foo"); 
    } 
}