c# generic with slight difference for types?

前端 未结 3 2064
庸人自扰
庸人自扰 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:26

    You can do it if you make an extra Func that performs transformation before calling the var action (which you should rename, because var is a C# keyword).

    Here is one approach that you could take:

    public static IEnumerator Tweeng(
        this float duration
    ,   System.Action varAction
    ,   T aa
    ,   T zz
    ) {
        Func transform = MakeTransform();
        float sT = Time.time;
        float eT = sT + duration;
        while (Time.time < eT) {   
            float t = (Time.time-sT)/duration;
            varAction(transform(aa, zz, t));
            yield return null;
        }
        varAction(zz);
    }
    
    private static Func MakeTransform() {
        if (typeof(T) == typeof(float)) {
            Func f = Mathf.SmoothStep;
            return (Func)(Delegate)f;
        }
        if (typeof(T) == typeof(Vector3)) {
            Func f = Vector3.Lerp;
            return (Func)(Delegate)f;
        }
        throw new ArgumentException("Unexpected type "+typeof(T));
    }
    

    It can even be done inline:

    public static IEnumerator DasTweeng( this float duration, System.Action vary, T aa, T zz )
        {
        float sT = Time.time;
        float eT = sT + duration;
    
        Func step;
    
        if (typeof(T) == typeof(float))
            step = (Func)(Delegate)(Func)Mathf.SmoothStep;
        else if (typeof(T) == typeof(Vector3))
            step = (Func)(Delegate)(Func)Vector3.Lerp;
        else
            throw new ArgumentException("Unexpected type "+typeof(T));
    
        while (Time.time < eT)
            {
            float t = (Time.time-sT)/duration;
            vary( step(aa,zz, t) );
            yield return null;
            }
        vary(zz);
        }
    

    Perhaps a more natural idiom is

        Delegate d;
    
        if (typeof(T) == typeof(float))
            d = (Func)Mathf.SmoothStep;
        else if (typeof(T) == typeof(Vector3))
            d = (Func)Vector3.Lerp;
        else
            throw new ArgumentException("Unexpected type "+typeof(T));
    
        Func step = (Func)d;
    

提交回复
热议问题