简体   繁体   English

c#泛型:我可以将重载方法合并为具有不同返回/输入数据类型的方法吗?

[英]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. 我有4种静态辅助方法,如果可能的话,我想将其合并为一种。 Each method is identical aside from the input parameter data type, and setting a value in the ReturnDto and the ReturnDto type. 除了输入参数数据类型以及在ReturnDto和ReturnDto类型中设置值之外,每种方法都是相同的。 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. 我对泛型不是很陌生,但是甚至不确定这是否在除4种强类型方法之外的高效方面是否可行。

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. 如果将T泛型类型参数 )替换为任何特定类型,则将获得所需的方法。 Think of T as a placeholder for any type. T视为任何类型的占位符。 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 ; 通过val的类型int推断T ; the compiler has enough information to figure out the type of T with you needing to explicitly state it. 编译器具有足够的信息来找出T的类型,而您需要明确声明它的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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