简体   繁体   中英

Ignorance of already inferred type parameters for generics

Simple code like this:

public TRes MyMethod<TIn, TRes>(TIn data)
{
//some logic
}

when it called in that way:

var result = MyMethod("test");

will warn with something like " type arguments can not be inferred from the usage, try to specify them explicitly ". While I see nothing bad in specifying TRes , why not compiler deduce TIn as it usually done?
If we say that generics signature must be remain unchanged and we can't write this

var result = MyMethod<int>("test");

then why not to omit TIn

var result = <_,int>MyMethod("test");

so TRes will be specified explicitly while TIn will be deduced.

Can I do something like this?

You can´t indicate only a few generic parameters while omitting others, you always have to specify either none at all and rely on the compiler to infer them for you (if this is even possible), or all at once.

If you just want to omit the result returned from your method, you can either define some arbitrary generic argument, such as object :

MyMethod<object>("Hello World");

or create an overload that simply calls the other overload and omits its result:

void MyMethod<T>(T t)
{
    MyMethod<object, T>(t);
}

This allows the following usages:

MyMethod<int>(3);
MyMethod(3);
var s = MyMethod<MyClass, int>(3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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