泛型函数接受 > 的类型参数
本文关键字:函数 类型参数 泛型 | 更新日期: 2023-09-27 18:35:50
我正在重构以下代码以使用泛型来减少方法:
class CInt { public int P1 { get; set; } }
class CDate { public DateTime P1 { get; set; } }
class CStr { public string P1 { get; set; } }
static IEnumerable<CInt> Fun(IEnumerable<CInt> p) { .... }
static IEnumerable<CDate> Fun(IEnumerable<CDate> p) { .... }
static IEnumerable<CStr> Fun(IEnumerable<CStr> p) { .... }
自:
interface IBase<T> { T P1 { get; set; } }
class CInt : IBase<int> { public int P1 { get; set; } }
class CDate : IBase<DateTime> { public DateTime P1 { get; set; } }
class CStr : IBase<string> { public string P1 { get; set; } }
static IEnumerable<T> Fun<T, U>(IEnumerable<T> p) where T : IBase<U> {
//....
var t = p.First().P1;
//....
return null;
}
var cints = new List<CInt> { new CInt() };
var result = Fun1<IBase<int>, int>(cints);
是否可以删除上述函数中的类型参数U
,因为T
可以决定U
是什么。或类似的东西
static IEnumerable<IBase<S>> Fun<IBase<S>>(IEnumerable<IBase<S>> p) { .... }
或者除非 C# 支持更高种类的类型,否则这是不可能的?
不确定"除非 C# 支持更高阶类型"是什么意思,但一种可能的解决方案是IBase<T>
扩展非泛型IBase
并将其用于对Fun
的约束:
interface IBase { }
interface IBase<T> : IBase { T P1 { get; set; } }
static IEnumerable<T> Fun<T>(IEnumerable<T> p) where T : IBase { .... }
当然,如果您在Fun
中使用IBase<T>
的泛型类型,则必须将 is 声明为第二个泛型参数。