我正在研究一个通用实用方法,它接受一个通用参数并返回一个通用类型——我希望这是有道理的!——但我希望返回类型与参数不同。
如果我用伪代码模拟它,我认为这应该是这样的:
public static IEnumerable<R> DoSomethingAwesome<T>(T thing)
{
var results = new List<R>();
for (int xx = 0; xx < 5; xx++)
{
results.Add(thing.ToRType(xx));
}
return results;
}
如果泛型无法推断返回类型,我该如何去做这样的事情呢?到目前为止,我的 Google-Fu 失败了。
最佳答案
// You need this to constrain T in your method and call ToRType()
public interface IConvertableToTReturn
{
object ToRType(int someInt);
}
public static IEnumerable<TReturn> DoSomethingAwesome<T, TReturn>(T thing)
where T : IConvertableToTReturn
{
Enumerable.Range(0, 5).Select(xx => thing.ToRType(xx));
}
关于c# - 在方法的参数和返回类型上使用不同的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6268555/