C# 泛型 : Can I combine overloaded methods into one with different return/input data types?

标签 c# generics overloading type-conversion strong-typing

我有 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 ) 替换为任何特定类型,您将获得您期望的方法。将 T 视为任何类型的占位符。如果任何类型都不是有效的,那么您可以限制它遵守某些规则;阅读 this获取更多信息。

另外值得注意的是,类型推断允许您调用此方法而无需实际声明泛型类型:

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

T是通过val的类型推断出来的,int;编译器有足够的信息来确定 T 的类型,您需要明确声明它。

关于C# 泛型 : Can I combine overloaded methods into one with different return/input data types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473827/

相关文章:

c# - 带有可选参数的构造函数违反了 new() 约束

java 8 lambda 泛型比较器 - 编译器警告

c++ - vector 排序 : swap overload

c# - 封装 Action<T> 和 Func<T>?

c# - Visual Studio Extensibility Package 2010 和 2012。有没有办法同时拥有一个包?

c# - 在 View 中显示来自 ViewModel 的平均值

java - 使用内部类作为 HashMap 的泛型参数

c# - 在C# asp.net中动态添加用户控件

c# - 使用 "DescribeInstanceStatus"例程过滤 EC2 实例 - AWS SDK

c++ - 如果 compile-time-constant 参数错误,则生成编译时错误