繁体   English   中英

通用函数接受类型参数 <T<U> &gt;?

[英]Generic function accept type parameter of <T<U>>?

我正在重构以下代码以使用通用方法来减少方法:

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);

由于T可以确定U是什么,因此是否可以删除上述函数中的类型参数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作为第二个通用参数。

暂无
暂无

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

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