在VS2015中:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TypeInference
{
public interface IResolvable<T>
{
T Resolve();
}
public class Trivial<T> : IResolvable<T>
{
private T it;
public T Resolve() { return it; }
public Trivial(T the) { it = the; }
}
public class TrivialText : Trivial<string>
{
public TrivialText(string s) : base(s) { }
}
class Program
{
static string f(IResolvable<string> s)
{
return s.Resolve();
}
static void Main(string[] args)
{
string s = "yet another string";
// error CS0305: Using the generic type 'Trivial<T>' requires 1 type arguments
Console.WriteLine(f(new Trivial("this is a string, right?")));
Console.WriteLine(f(new Trivial(s)));
// ok
Console.WriteLine(f(new Trivial<string>("this is a string, right?")));
// OK
Console.WriteLine(f(new TrivialText("this is a string, right?")));
}
}
}
这里的类型推断似乎应该是显而易见的。前两行显然是一个字符串,但两种形式都坚持我声明了type参数。这似乎与这里所作的陈述相矛盾:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods
您也可以省略type参数,编译器会推断它。 以下对Swap的调用等同于之前的调用
我做错了吗?
TIA