c# 泛型:我可以将重载方法组合成一个具有不同 return/input 数据类型的方法吗?
c# Generics : Can I combine overloaded methods into one with different return/input data types?
我有 4 个静态辅助方法,如果可能的话我想合并为一个。除了输入参数数据类型以及在 ReturnDto 和 ReturnDto 类型中设置值外,每个方法都是相同的。我对泛型还很陌生,但我什至不确定除了拥有 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 };
}
是:
private static ReturnDto<T> MethodName<T>(T val)
如果您替换为 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 以获得更多信息。
另外值得注意的是,类型推断允许您调用此方法而无需实际声明泛型类型:
var returnDto = MethodName(1); //instead of MethodName<int>(1)
T
是通过val
的类型推断出来的,即int
;编译器有足够的信息来确定 T
的类型,你需要明确说明它。
我有 4 个静态辅助方法,如果可能的话我想合并为一个。除了输入参数数据类型以及在 ReturnDto 和 ReturnDto 类型中设置值外,每个方法都是相同的。我对泛型还很陌生,但我什至不确定除了拥有 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 };
}
是:
private static ReturnDto<T> MethodName<T>(T val)
如果您替换为 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 以获得更多信息。
另外值得注意的是,类型推断允许您调用此方法而无需实际声明泛型类型:
var returnDto = MethodName(1); //instead of MethodName<int>(1)
T
是通过val
的类型推断出来的,即int
;编译器有足够的信息来确定 T
的类型,你需要明确说明它。