[英]Generic function accept type parameter of <T<U>>?
I'm refactoring the following code to use generic to reduce the methods: 我正在重构以下代码以使用通用方法来减少方法:
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) { .... }
To: 至:
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);
Is it possible to remove the type parameter U
in above function since T
can decide what U
is. 由于
T
可以确定U
是什么,因此是否可以删除上述函数中的类型参数U
Or something like 或类似的东西
static IEnumerable<IBase<S>> Fun<IBase<S>>(IEnumerable<IBase<S>> p) { .... }
Or it's not possible unless C# support higher kinded type? 或者,除非C#支持更高种类的类型,否则这是不可能的?
Not sure what you mean by "unless C# support higher order type", but one possible solution is to have IBase<T>
extend a non-generic IBase
and use that for your constraint on Fun
: 不确定“除非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 { .... }
Of course, if you use the generic type of IBase<T>
in Fun
then you have to declare is as a second generic parameter. 当然,如果在
Fun
使用 IBase<T>
的通用类型,则必须声明is作为第二个通用参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.