c# generic with slight difference for types?

前端 未结 3 2062
庸人自扰
庸人自扰 2020-12-19 14:16

Notice the two extensions, one for float, one for Vector3.

Notice there\'s only a slight difference in the var( call.

In c# could these be writt

3条回答
  •  温柔的废话
    2020-12-19 14:31

    You can define your method as follows:

    public static IEnumerator Tweeng(this float duration,
             System.Action var, T aa, T zz, Func thing)
    {
        float sT = Time.time;
        float eT = sT + duration;
    
        while (Time.time < eT)
        {
            float t = (Time.time - sT) / duration;
            var(thing(aa, zz, t));
            yield return null;
        }
    
        var(zz);
    }
    

    And then using it:

    float a = 5;
    float b = 0;
    float c = 0;
    a.Tweeng(q => {}, b, c, Mathf.SmoothStep);
    

    Or:

    float a = 0;
    Vector3 b = null;
    Vector3 c = null;
    a.Tweeng(q => {}, b, c, Vector3.Lerp);
    

    Alternatively, if you want to get rid of the method passing, you can have simple overloads to handle it:

    public static IEnumerator Tweeng(this float duration, System.Action var, float aa, float zz)
    {
        return Tweeng(duration, var, aa, zz, Mathf.SmoothStep);
    }
    public static IEnumerator Tweeng(this float duration, System.Action var, Vector3 aa, Vector3 zz)
    {
        return Tweeng(duration, var, aa, zz, Vector3.Lerp);
    }
    
    private static IEnumerator Tweeng(this float duration,
             System.Action var, T aa, T zz, Func thing)
    {
        float sT = Time.time;
        float eT = sT + duration;
    
        while (Time.time < eT)
        {
            float t = (Time.time - sT) / duration;
            var(thing(aa, zz, t));
            yield return null;
        }
    
        var(zz);
    }
    

    And then using it:

    float a = 5;
    float b = 0;
    float c = 0;
    a.Tweeng(q => {}, b, c);
    

    Or:

    float a = 0;
    Vector3 b = null;
    Vector3 c = null;
    a.Tweeng(q => {}, b, c);
    


    Stub methods to compile in LINQPad/without unity:

    public class Mathf { public static float SmoothStep(float aa, float zz, float t) => 0; }
    public class Time { public static float time => DateTime.Now.Ticks; }
    public class Vector3 { public static Vector3 Lerp(Vector3 aa, Vector3 zz, float t) => null; }
    

提交回复
热议问题