简体   繁体   中英

Method receiving and returning generic type - how to do it?

I have a class Frame that holds some samples. I want to have a method AsType that converts these samples to another numeric type.

I tried this, but it doesn't work because The type or namespace 'TargetType' cannot be found . Also, I am a bit lost as to why it didn't work and how could I have figured out the right way to think about it and get it right.

public class Frame<T>
{
    public T[] Samples { get; protected set; }

    public Frame(IEnumerable<T> Samples)
    {
        Samples = Samples.ToArray();
    }

    public Frame<TOut> AsType(Type TOut)
    {
        // line below doesn't work
        return new Frame<TOut>(Samples.Select(s => (TOut)s));
    }
}

You don't need a method parameter for this, but a generic parameter :

                        //don't miss this parameter!
public Frame<TOut> AsType<TOut>()
{
    return new Frame<TOut>(Samples.Select(s => (TOut)s));
}

TOut is the generic parameter, so there is no need for an extra type parameter. But note that there must exist an explicit convertion for the type you call this method with, otherwise (TOut)s will throw an InvalidCastException .

And you could change the code using the Cast<> extension:

public Frame<TOut> AsType<TOut>()
{
    return new Frame<TOut>(Samples.Cast<TOut>());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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