简体   繁体   中英

c# Generics : Can I combine overloaded methods into one with different return/input data types?

I have 4 static helper methods I want to combine into one if possible. Each method is identical aside from the input parameter data type, and setting a value in the ReturnDto and the ReturnDto type. I'm fairly new to Generics but not even sure if this is doable in an efficient matter other than having 4 strongly typed methods.

private static ReturnDto<int> MethodName(int val)
private static ReturnDto<string> MethodName(string val)
private static ReturnDto<bool> MethodName(bool val)
private static ReturnDto<DateTime> MethodName(DateTime val)
{
    //do some stuff here...
    return new ReturnDto<DateTime> { Val = val, Val2 = val2, Val3 = val3 };
}

Yes:

private static ReturnDto<T> MethodName<T>(T val)

If you substitute T ( generic type parameter ) with any specific type you will get the method you expect. Think of T as a placeholder for any type. If not any type is valid then you can constraint it to comply with certain rules; read this for more information.

Also worth noting, is that type inference allows you to call this method without actually having to state the generic type:

var returnDto = MethodName(1); //instead of MethodName<int>(1)

T is inferred through the type of val which is int ; the compiler has enough information to figure out the type of T with you needing to explicitly state it.

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