简体   繁体   中英

Can you use the same generic type MULTIPLE TIMES in a generic class declaration?

I would like to have an identity translator that would just return the type that was passed in. I have an interface:

 public interface IDataTranslator<TFrom, TTo>  {
        TTo Translate(TFrom fromObj);
    }

And I would like my class to just act like an identity translator, ie just return the parameter so something like this (of course this doesn't compile):

public class IdentityDataTranslator<T, T> : IDataTranslator<T, T> {
        public T Translate(T fromObj) {
            return fromObj;
        }
}

Just can't seem to get the syntax correct here...

Just don't define the second type argument on the implementing class; you already have what you need with one:

public class IdentityDataTranslator<T> : IDataTranslator<T, T> {
        public T Translate(T fromObj) {
            return fromObj;
        }
}

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