具有多种类型的C#泛型类型推断 [英] C# Generic Type Inference With Multiple Types

查看:55
本文介绍了具有多种类型的C#泛型类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下通用方法将一种类型的输入对象序列化为超类型,如下所示:

I have the following generic method for serialising an input object of one type as a super-type as follows:

public string SerialiseAs<TResult, TInput>(TInput input) where TInput : TResult
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(TResult));
    MemoryStream stream = new MemoryStream();
    ser.WriteObject(stream, input);
    stream.Position = 0;
    StreamReader reader = new StreamReader(stream);
    return reader.ReadToEnd();
}

我必须调用此方法,同时指定两种通用类型,如下所示:

I have to call this method specifying both generic types as follows:

MySubType x = new MySubType();
string json = SerialiseAs<MySuperType, MySubType>(x);

我的问题是,为什么不能在这种情况下推断 TInput ?是因为 TResult 实际上没有用作返回类型吗?以下代码更简洁,但由于缺少输入类型而无法编译:

My question is, why can't TInput be inferred in this situation? Is it because TResult isn't actually used as the return type? The following code is cleaner but won't compile because of the missing input type:

MySubType x = new MySubType();
string json = SerialiseAs<MySuperType>(x);

推荐答案

我的问题是,为什么不能在这种情况下推断TInput?

My question is, why can't TInput be inferred in this situation?

可以-无法推断的是 TResult ,并且无法指定部分"推断.

It can - it's TResult which can't be inferred, and there's no way of specifying "partial" inference.

您有时可以做的就是将类型参数分为通用的 type 和通用的 method .d结尾:

What you can sometimes do is separate the type parameters into ones for a generic type and ones for a generic method, so you'd end up with:

// Explicitly state TResult, and infer TInput
Serializer<MySuperType>.Serialize(x);

这篇关于具有多种类型的C#泛型类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆